CSS - z-index의 이해, 사용 방법

반응형

 

z-index란?

  • 자식 또는 하위의 아이템의 Z축 순서를 지정하는 것
  • 값을 가진 요소가 클수록 작은 요소를 덮음
    • 즉, 겹쳐진 여러개의 요소들의 보여질 순서를 정함

구문

z-index 설정 값 설명

  • auto : 부모의 요소와 같은 값
  • 숫자 : 숫자가 높을수록 우선 순위 높음
    • 숫자와 auto 모두 같은 값일 경우, 더 마지막에 정의한 요소가 우선순위가 높음 (가장 위에 보인다는 뜻)
  • inherit : 상위 요소의 값 상속
  • initial : 기본 값 사용
  • unset : 상속 값이 있으면 상속 값 적용, 아니면 기본 값 사용 (inherit or initial)
/* 키워드 값 */
z-index: auto;

/* <integer> 값 */
z-index: 0;
z-index: 3;
z-index: 289;
z-index: -1; /* 음수 값으로 우선순위를 낮출 수 있음 */

/* 전역 값 */
z-index: inherit;
z-index: initial;
z-index: unset;

사용 예시

z-index 미적용

  • css 스타일
/* 점선 사각형 생성 */
.dashed-box {
  border: dashed;
  width: 15em;
  height: 3em;
}

/* 노란색 사각형 생성 */
.gold-box {
  position: absolute;
  background: gold;
  left: 60px;
  height: 3em;
  top: 2em;
}

/* 녹색 사각형 생성 */
.green-box {
  position: absolute;
  background: lightgreen;
  height: 7em;
  opacity: 0.9;
}

 

  • html
<!-- 점선 사각형 생성 -->
<div class="dashed-box">Dashed box
    <!-- 노란색 사각형 생성 -->
    <span class="gold-box">Gold box</span>
    <!-- 녹색 사각형 생성 -->
    <span class="green-box">Green box</span>
</div>

<!-- 원래의 순서 : 녹색 > 노란색 > 점선 순 -->

 

  • z-index 미적용 화면


z-index 적용

  • css 스타일
/* 점선 사각형 생성, z-index = 1 */
.dashed-box {
  z-index: 1;
  border: dashed;
  width: 15em;
  height: 3em;
}

/* 노란색 사각형 생성, z-index = 3 */
.gold-box {
  position: absolute;
  z-index: 3;
  background: gold;
  left: 60px;
  height: 3em;
  top: 2em;
}

/* 녹색 사각형 생성, z-index = 2 */
.green-box {
  position: absolute;
  z-index: 2;
  background: lightgreen;
  height: 7em;
  opacity: 0.9;
}

/* z-index는 높을수록 우선순위가 높으므로 노란색, 녹색, 점선 사각형순으로 보인다. */

 

  • html
<!-- 점선 사각형 생성 -->
<div class="dashed-box">Dashed box
    <!-- 노란색 사각형 생성 -->
    <span class="gold-box">Gold box</span>
    <!-- 녹색 사각형 생성 -->
    <span class="green-box">Green box</span>
</div>

<!-- z-index가 적용된 순서 : 노란색 > 녹색 > 점선 순 -->

 

  • z-index 적용
    • 노란색 > 녹색 > 점선


전체 코드

<!-- hello.html -->
<html>
    <head>
        <style>
            .dashed-box {
                z-index: 1;
                border: dashed;
                width: 15em;
                height: 3em;
            }
            .gold-box {
                position: absolute;
                z-index: 3;
                background: gold;
                left: 60px;
                height: 3em;
                top: 2em;
            }
            .green-box {
                position: absolute;
                z-index: 2;
                background: lightgreen;
                height: 7em;
                opacity: 0.9;
            }
        </style>
    </head>
<body>
    <div class="dashed-box">Dashed box
        <span class="gold-box">Gold box</span>
        <span class="green-box">Green box</span>
    </div>
</body>
</html>

참고

  • mozilla.org - CSS - z-index

https://developer.mozilla.org/ko/docs/Web/CSS/z-index

반응형