[CSS] 배경에만 opacity 적용하기

nagosu·2024년 6월 5일
1
post-thumbnail

문제 발생

img 태그를 background-image와 opacity를 적용한 div 태그로 감싸주었더니 이미지 마저 투명도가 적용되는 현상이 발생했다.

{/* 관전모드 */}
<div css={styles.headerSpectator}>
	<img src={spectatorMode} alt='' />
</div>

{/* 문제풀이중 */}
<div css={styles.headerStudying}>
	<img css={styles.studying} src={studyingMode} alt='' />
</div>
import { css } from "@emotion/react";

const styles = {
  headerSpectator: css`
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 34px;
    position: absolute;
    background-image: linear-gradient(
      271deg,
      #6b04bb 0%,
      rgba(107, 4, 187, 0) 100%
    );
    opacity: 0.5;
    top: 0;
  `,
  headerStudying: css`
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 34px;
    position: absolute;
    background-image: linear-gradient(
      271deg,
      #005dff 0%,
      rgba(0, 93, 255, 0) 100%
    );
    opacity: 0.5;
    top: 0;
  `,
  studying: css`
    width: 75.2px;
  `,
};

export { styles };

해결한 방법

가상요소 ::after 사용

import { css } from "@emotion/react";

const styles = {
  headerSpectator: css`
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 34px;
    position: absolute;
    isolation: isolate;
    top: 0;

    &::after {
      content: "";
      position: absolute;
      background-image: linear-gradient(
        271deg,
        #6b04bb 0%,
        rgba(107, 4, 187, 0) 100%
      );
      z-index: -1;
      inset: 0;
      opacity: 0.5;
    }
  `,
  headerStudying: css`
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 34px;
    position: absolute;
    isolation: isolate;
    top: 0;

    &::after {
      content: "";
      position: absolute;
      background-image: linear-gradient(
        271deg,
        #005dff 0%,
        rgba(0, 93, 255, 0) 100%
      );
      z-index: -1;
      inset: 0;
      opacity: 0.5;
    }
  `,
  studying: css`
    width: 75.2px;
  `,
};

export { styles };

::after 가상 요소는 headerSpectator 또는 headerStudying 요소의 마지막 자식 요소로 추가된다.

여기서 중요한 것은 isolation 속성이다.

isloation 속성은 해당 요소와 자식 요소가 독립된 스택 컨텍스트를 가지도록 한다.

이로 인해서 z-index 값이 다른 요소들과 겹치지 않는다.

가상요소에 background-imageopacity를 적용하고 z-index를 -1로 설정해 부모 요소의 뒤로 위치시킨다.

결과

뒤에 배경은 opacity가 적용되고 이미지(관전모드/문제풀이중)은 선명하게 나왔다!

profile
프론트엔드 개발자..일걸요?

0개의 댓글

관련 채용 정보