본문 바로가기
CSS

Z-index와 Stacking Context(스태킹 컨텍스트)

by F.E.D 2021. 3. 1.

Z-index를 사용할 때 Stacking Context를 고려하십니까?

아마 대부분 스태킹 컨텍스트에 의해서 z-index의 순서가 결정된 다는 것을 알고 있을겁니다.

여기서 더 나아가서 또 놀라운 사실이 있습니다.

스택 컨텍스트 생성에 있어서 놀라운 예외가 있습니다.

스택 컨텍스트 생성을 발생시키지 않게 함으로 인해서 내부 콘텐츠와 z-index를 교차할 수 있습니다.

<div class="scroll-area">
    <div class="vertical-bar"></div>
    <div class="vertical-bar"></div>
    <div class="vertical-bar"></div>
    <div class="vertical-bar"></div>
</div>

<div class="yellow-horizontal-bar">~~JUST PASSING THROUGH~~</div>
.scroll-area {
  overflow: scroll;
  border: 3px solid salmon;
  width: 18ex;
  height: 15ex;
  margin-left: 2ex;
}

.scroll-area .vertical-bar {
  position: relative;
  float: left;
  height: 50ex;
  width: 4ex;

  background: repeating-linear-gradient(
    120deg,
    salmon 0px, salmon 10px,
    orange 10px, orange 20px
  );
}

.scroll-area .vertical-bar:nth-child(even) {
  z-index: 4;
  opacity: 0.9;
}

.yellow-horizontal-bar {
  margin-top: -10ex;
  margin-bottom: 10ex;
  max-width: 30ex;
  background: #EEDD88;

  position: relative;
  z-index: 2;
}

 

See the Pen vertical-bar z-index by YoungMinKim (@oinochoe) on CodePen.

 

 

위와 같은 예외는 웹 환경을 더욱 더 복잡하게 만들었습니다.

결국 이러한 예외들에 대한 호환성을 극대화하기로 결정한 것입니다.

 

또 다른 예외가 있습니다.

 

위의 상황에서는 z-index가 -2인 두개의 스태킹 컨텍스트가 모두 blue box(z-index 0상태) 아래에 있어야 하는데 붉은 박스가 최상위로 올라와 있습니다.

 

트릭은 바로 transform-style: preserve-3d 입니다.

 

See the Pen z-index transform preserve-3d by YoungMinKim (@oinochoe) on CodePen.

transform-style preserve-3d를 통해 3d 공간을 만든 상태에서 붉은 색상의 박스를 translateZ축 양수 방향으로 밀어냅니다.

스태킹 컨텍스트의 기본규칙을 벗어나는 이러한 트릭들은 호환성에 위배되긴 하지만 알아두면 유용합니다.

 

이상입니다.

 

출처 : abandonedwig.info/blog/2020/07/03/css-painting-order.html

댓글