position 속성을 사용하면 요소를 문서흐름에서 벗어나게 하여 위치를 변경할 수 있다. 이렇게 위치를 변경했을 때 어떤 요소가 어떤 요소보다 더 위에 있는지 알 수 있도록 해주는 것이 Z-index속성이다. xyz축에서 그 z축이라고 이해하면 될 듯 하다.
기본값은 auto, 즉 0이다. z-index가 더 높은 요소는 값이 더 낮은 요소보다 위에 배치된다.
코드 예제
<body>
<div id="first">Element 1</div>
<div id="second">Element 2</div>
</body>
div {
width: 200px;
height: 200px;
text-align: center;
color: white;
}
#first {
background-color: rgb(55, 117, 209);
}
#second {
background-color: rgb(233, 137, 59);
}
기본적으로 #first, #second 두 요소 모두 문서 흐름을 따르며 Element 1이 먼저 표시되고 Element 2가 두 번째로 표시된다.
#second의 css를 이렇게 바꿔주면
#second {
background-color: rgb(233, 137, 59);
position: absolute;
top: 0;
left: 0;
}
#second는 문서 흐름에서 벗어나고, #first 위에 표시된다.
이때 z-index: 1을 #first에 추가해도 z-index는 기본 값 position: static을 제외하고 배치된 요소에만 영향을 미치므로 z-축을 따라 요소의 순서가 변경되지 않는다. 그러므로 z-index: 1을 추가한 채로 #first에도 position: absolute;를 적용시키면
#first {
background-color: rgb(55, 117, 209);
position: absolute;
z-index: 1;
}
#first가 위쪽으로 올라오게 된다.
+position: relative로 코드를 바꾸면 #first를 기준으로 #first가#second 위에 배치된다.