TIL-2022-05-09 Stacking Context와 Z-index 없이 Stacking
Stacking Context
Stacking Context는 z-축으로 HTML 요소들이 쌓이는 개념을 의미한다.
쌓임 맥락은
- 문서의 root document(<html>)
- position이 absolute, relative인 z-index가 auto가 아닌 요소
- position이 fixed, sticky인 요소
- z-index가 auto가 아닌 grid, flex 컨테이너의 자손
- opacity < 1인 요소
등.... 의 요소에 형성된다.
쌓임 맥락은 다른 쌓임 맥락을 포함할수 있으며, 합쳐지면 계층을 형성함
sibling과는 완전히 독립적임 -> 오직 부모 컨테이너만 영향을 줌
각 쌓임 맥락은 독립적이라 쌓고 나서는 아예 부모 컨테이너에 넣어버림
모든 요소가 쌓임 맥락을 가지고 있는건 아니라 쌓임 맥락의 계층 구조는 HTML 요소 계층의 부분 집합이고, 쌓임맥락이 없는 요소들은 부모 요소에 동화됨(assilmilated)
이것을 보면 이해가 쉽다!
이 DIV들은 모두 쌓임 맥락을 각각 가지고 있는데,
DIV1, 2, 3은 각각 sibling들이며 그래서 z-index의 순서대로 덮히게 된다.
그러나 DIV 4,5,6은 DIV 3안에 들어있는 요소들인데, DIV 6의 경우 z-index가 6으로 DIV 1보다 큰데, 부모 요소인 DIV 3에 속해있으므로 덮여지게 된다. (DIV 2와 5도 비슷한 맥락)
z-index를 통해서 쌓임을 비교할떄는 동일한 쌓임 맥락 안에서만 비교한다.
<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>
z-index 없이 stacking하기
주로 덮어야되는 요소들을 결정할떄 z-index를 통해서 설정하곤 한다.
그러나 그러지 않고도 이를 결정하는 방법이 있다.
z-index가 결정되지 않았을 경우,
- root 요소의 background, border
- html에 나타나는 순서대로 non-positioned blocks,
- html에 나타나는 순서대로 positioned elements
대로 쌓이게 된다.
여기서 positioned, non-positioned에서 positioned는 static을 제외한 absolute, fixed, relative, sticky를 모두 뜻하고, non-positioned는 static 하나 뿐이다.
따라서 DIV 네이밍이 html 순서대로라고 하면,
static을 가진 div는 선언 순서대로 제일 밑에 딸리게 되고, 그 다움부터는 선언 순서대로 positioned element가 깔리게 된다.
따라서 sibling관계의 요소들은 선언 순서에 따라서 깔리는게 달라지기도 하며, 이를 고려하여 코드를 짜면 z-index없이도 원하는 바를 얻을수 있다.