【Css】Z-index에 대해 No-2

10578 단어 SassCSS

처음에



css에서 요소의 스택 순서를 결정하는 z-index. 단지 z-index에 값을 지정하는 것만으로는 작동하지 않는 장면이 있습니다. 그 원인과 이유에 대해 배운 내용을 써 보았습니다.

※내용에 실수등이 있는 경우는 지적을 잘 부탁드립니다.

마지막 기사



z-index와 position



z-index를 적용하려면 position이 static이 아니어야 합니다.
<body>
  <div class="red"></div>
  <div class="blue"></div>
</body>

position을 absolute로 하고, red의 z-index를 5, blue의 z-index를 2로 합니다.
.red {
  width: 100px;
  height: 100px;
  background-color: red;
  margin-top: 50px;
  position: absolute;
  z-index: 5;
}

.blue {
  width: 100px;
  height: 100px;
  background-color: blue;
  position: absolute;
  margin-bottom: 50px;
  z-index: 2;
}

red의 z-index가 5로, blue의 2보다 높기 때문에, red가 blue 위에 타고 있습니다.

position을 주석 처리해 봅니다.
.red {
  width: 100px;
  height: 100px;
  background-color: red;
  margin-top: 50px;
  /* position: absolute; */
  z-index: 1;
}

.blue {
  width: 100px;
  height: 100px;
  background-color: blue;
  /* position: absolute; */
  margin-bottom: 50px;
  z-index: 2;
}


빨간색 아래에 파란색이 배치되고 빨간색과 파란색이 겹치지 않는 상태입니다. position을 지정하지 않으면 요소는 디폴트의 position인 static이 적용되어 각각의 요소 그 자체가 개별의 context를 생성하기 때문입니다.

z-index와 context



복수의 요소(태그)가 하나의 context를 생성하기 위해서는, 요소끼리가 siblings(형제 관계)일 필요가 있습니다. red과 green은 같은 계층에 있으며 형제 관계입니다. bule은 red의 아이로, yellow는 blue의 아이인 이하와 같은 계층 구조를 가지는 html 문서가 있다고 합니다.
<body>
  <div class="red">
    <div class="blue">
      <div class="yellow">
    </div>
    </div>
  </div>
  <div class="green">
  </div>
</body>

레드를 맨 위로 만들고 싶기 때문에 z-index를 10으로 설정하고 그 아래에 green이 겹치도록 z-index를 4로 만듭니다. 그 아래에는 한층 더 blue가 오도록(듯이) z-index를 2로 지정해, 마지막으로 yellow를 1로 해 맨 아래로 하고 싶습니다.
그림으로 나타내면 다음과 같습니다. (예상도)


실제로 그것에 맞게 CSS를 작성합니다.
.red {
  width: 100px;
  height: 100px;
  background-color: red;
  margin-top: 40px;
  position: relative;
  z-index: 10;
}

.blue {
  width: 100px;
  height: 100px;
  background-color: blue;
  position: absolute;
  top: 30px;
  margin-bottom: 50px;
  z-index: 2;
}

.yellow {
  width: 100px;
  height: 100px;
  background-color: yellow;
  margin-left: 50px;
  position: absolute;
  z-index: 1;
}

.green {
  width: 100px;
  height: 100px;
  background-color: green;
  position: absolute;
  top: -30px;
  z-index: 4;
}

결과는 다음과 같습니다.

예상과 달리 red 아래에 green이 오고 있지만, 하단에 위치한 yellow는 blue 위에 있습니다. 또한 red는 z-index가 10임에도 불구하고 z-index가 2의 blue보다 아래입니다. 왜 이렇게 될까요?

context는 같은 계층(형제 관계)에서만 생성된다



context는 동일한 계층 구조가 아니면 생성되지 않습니다. 위의 예에서 red과 green은 동일한 계층 구조이고 blue와 yellow는 각각 부모와 자식 관계의 다른 계층입니다. red와 green은 하나의 컨텍스트를 생성하고 blue, yellow는 각각의 개별 컨텍스트를 생성합니다. 총 세 개의 컨텍스트가 있습니다. red와 green이 생성하는 context상에서 z-index에 의한 요소의 상하 관계가 정해져, blue의 context와 yellow의 context는 차례대로 red와 green이 생성하는 context 위에 적층되기 때문에, blue 위에 yellow가 타고 있는 형태가 됩니다.



참고 사이트



htps : //로 ゔぇぺぺr. 모잖아. 오 rg / 그럼 / cs / u b / Cs / ~ 어서 x
htps : // 코 s. 코 m / r 치 c ぇ s / 부이 ld ぇ b 해서 s / 오페라 치온 / cs s / 4- 레 아소 s ~ . HTML
htps : // 그럼 아안. 이. jp / ぇ bp 로즈 c 치온 / f 롱텐 d / ~ 어서 x /
htps : // 이 m / 17296 / ms / 42 62989193504d512c7

좋은 웹페이지 즐겨찾기