🌿  쌓임맥락(Stacking Context)

쌓임맥락이란 ?

쌓임 맥락은 HTML요소가 화면에 쌓이는 방식을 정의하는 개념입니다. 태그들을 쌓아 올리는 도화지라고 생각하시면 되겠네요.

특정 요소가 새로운 쌓임 맥락을 생성하면, 그 요소와 그 자식 요소들은 다른 쌓임 맥락을 가진 요소들과는 독립적으로 쌓이게 됩니다! 그래서 어떤 경우에는 아무리 z-indexz-index: 999까지 높은 숫자로 정해주어도 원하는 쌓임이 구현되지 않을 수 있습니다.

새로운 쌓임 맥락은 다음 경우에 생성 된답니다. (지금은 이런게 있구나~ 하고 넘어가주세요!)

아래 예시에서, 모든 요소는 각자의 포지션과 z-index로 인해 자신의 쌓임 맥락을 형성합니다.

루트
	DIV #1
	DIV #2
	DIV #3
		DIV #4
		DIV #5
		DIV #6

스크린샷 2024-08-06 오전 11.40.07.png

<!DOCTYPE html>
<div id="div1">
  <h1>Division Element #1</h1>
  <code
    >position: relative;<br />
    z-index: 5;</code
  >
</div>

<div id="div2">
  <h1>Division Element #2</h1>
  <code
    >position: relative;<br />
    z-index: 2;</code
  >
</div>

<div id="div3">
  <div id="div4">
    <h1>Division Element #4</h1>
    <code
      >position: relative;<br />
      z-index: 6;</code
    >
  </div>

  <h1>Division Element #3</h1>
  <code
    >position: absolute;<br />
    z-index: 4;</code
  >

  <div id="div5">
    <h1>Division Element #5</h1>
    <code
      >position: relative;<br />
      z-index: 1;</code
    >
  </div>

  <div id="div6">
    <h1>Division Element #6</h1>
    <code
      >position: absolute;<br />
      z-index: 3;</code
    >
  </div>
</div>

* {
  margin: 0;
}
html {
  padding: 20px;
  font:
    12px/20px Arial,
    sans-serif;
}
div {
  opacity: 0.7;
  position: relative;
}
h1 {
  font: inherit;
  font-weight: bold;
}
#div1,
#div2 {
  border: 1px dashed #696;
  padding: 10px;
  background-color: #cfc;
}
#div1 {
  z-index: 5;
  margin-bottom: 190px;
}
#div2 {
  z-index: 2;
}
#div3 {
  z-index: 4;
  opacity: 1;
  position: absolute;
  top: 40px;
  left: 180px;
  width: 330px;
  border: 1px dashed #900;
  background-color: #fdd;
  padding: 40px 20px 20px;
}
#div4,
#div5 {
  border: 1px dashed #996;
  background-color: #ffc;
}
#div4 {
  z-index: 6;
  margin-bottom: 15px;
  padding: 25px 10px 5px;
}
#div5 {
  z-index: 1;
  margin-top: 15px;
  padding: 5px 10px;
}
#div6 {
  z-index: 3;
  position: absolute;
  top: 20px;
  left: 180px;
  width: 150px;
  height: 125px;
  border: 1px dashed #009;
  padding-top: 125px;
  background-color: #ddf;
  text-align: center;
}

DIV#4 ,5,6 은 DIV#3의 자식이므로 DIV #3 내부에서만 쌓임을 처리했다는 것을 이해하는것이 중요합니다!