목차
- z-index 정의
- z-index 구문
- z-index 예제1 - 요소가 1개일 땐 무의미
- z-index 예제2 - 4번째가 가장 위에 위치
- z-index 예제3 - 3번째가 가장 위에 위치
- z-index 예제4 - 부모자식 계층적 요소간엔 작동 X
z-index 정의
요소끼리 겹칠 때 상하 지정. (= 요소간 상대적 층간 위치 지정.)
즉,
몇 개의 요소가
position 속성에 의해 위치 겹칠 때,
z-index 숫자가 더 높은 요소가 더 앞쪽에 노출 됨.
1.
position 속성과 함께 사용. ★★★★★즉, 아래 경우에 적용됨.
- position: absolute;
- position: relative;
- position: fixed;
- position: sticky;
- flex items (= display:flex 요소의 직접 자식요소들)
단, 한 요소 안 계층적 요소간엔 작동 X. (예제4)
2.
z-index 값 없이 2개의 position 된 요소가 서로 겹칠 시,
HTML 코드 순서 마지막에 위치한 요소가 더 앞에 배치됨.
3.
- 기본값: auto
- 상속여부: X
- 애니효과: O
- CSS버전: CSS2
- JS구문 : object.style.zIndex="-1"
4.
5. MDN z-index 예제보기
z-index 구문
selector {z-index: auto|number|initial|inherit;}
[속성값]
auto
문서 흐름에 따른 기본 위치에 위치 (기본값)
number숫자 클수록 겹쳤을 때 위에 위치.
- 음수 가능. 이 경우 다른 요소들보다 밑면에 위치.
initial
이 속성의 기본값으로 설정.
inherit
부모요소 속성값 상속.
z-index 예제1 - 요소가 1개일 땐 무의미
<style>
#layer1 {
background-color:red;
width:200px; height:200px;
position:absolute;
top:106px;
left:209px;
z-index:1;
}
</style>
<div id="layer1">홈짱닷컴 (homzzang.com)</div>
z-index 예제2 - 4번째가 가장 위에 위치
<style>
div {
width:200px;
height:200px;
position:absolute;
}
#layer1 {
background-color:red;
left:209px;
top:106px;
z-index:1;
}
#layer2 {
background-color:blue;
left:265px;
top:142px;
z-index:2;
}
#layer3 {
background-color:magenta;
left:322px;
top:197px;
z-index:3;
}
#layer4 {
background-color:yellow;
left:379px;
top:247px;
z-index:4;
}
</style>
<div id="layer1"></div>
<div id="layer2"></div>
<div id="layer3"></div>
<div id="layer4"></div>
z-index 예제3 - 3번째가 가장 위에 위치
<style>
div {
width:200px;
height:200px;
position:absolute;
}
#layer1 {
background-color:red;
left:209px;
top:106px;
z-index:1;
}
#layer2 {
background-color:blue;
left:265px;
top:142px;
z-index:2;
}
#layer3 {
background-color:magenta;
left:322px;
top:197px;
z-index:4;
}
#layer4 {
background-color:yellow;
left:379px;
top:247px;
z-index:3;
}
</style>
<div id="layer1"></div>
<div id="layer2"></div>
<div id="layer3"></div>
<div id="layer4"></div>
z-index 예제4 - 부모자식 계층적 요소간엔 작동 X
<style>
div {width:100px; height:100px; position:absolute;}
.hz {background:white; top:100px; left:100px; }
.a {background:red; top:0px; left:0px; z-index:3}
.b {background:blue; top:30px; left:30px; z-index:2}
.c {background:green; top:30px; left:30px; z-index:1}
</style>
<div class="hz">
<div class="a">a
<div class="b">b
<div class="c">c</div>
</div>
</div
</div>
결과 보기
※ 주의: a요소의 z-index 값이 가장 크지만, 자식요소가 부모요소 위에 배치 됨.