Computer >> 컴퓨터 >  >> 프로그래밍 >> CSS

CSS z-index 속성으로 요소 겹침 제어하기

CSS의 z-index 속성을 사용하면 개발자가 여러 요소를 서로 겹쳐 쌓는(stacking) 레이아웃을 손쉽게 구현할 수 있습니다. z-index는 양수 또는 음수 값을 가질 수 있으며, 값이 클수록 화면에서 앞쪽(위)에 배치됩니다.

z-index 사용 시 주의사항

참고: 서로 겹치는 요소들에 z-index가 지정되어 있지 않다면, 문서(document)에서 마지막에 작성된 요소가 가장 위에 표시됩니다.

예제 1: 음수 z-index로 요소 쌓기

다음은 z-index 속성을 활용한 첫 번째 예제입니다.

<!DOCTYPE html>
<html>
<head>
<style>
p {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
div{
    margin: auto;
    position: absolute;
    top:0;
    left: 0;
    right: 0;
    bottom: 0;
}
div:first-child {
    background-color: orange;
    width: 270px;
    height: 120px;
    z-index: -2;
}
div:last-child {
    width: 250px;
    height: 100px;
    z-index: -1;
    background-color: turquoise;
}
</style>
</head>
<body>
<div></div>
<p>Fortran was originally developed by a team at IBM in 1957 for scientific calculations...................</p>
<div>
</div>
</body>
</html>

실행 결과

위 코드의 실행 결과는 다음과 같습니다.

CSS z-index 속성으로 요소 겹침 제어하기

이 예제에서는 두 개의 div 요소에 각각 z-index: -2z-index: -1을 적용했습니다. 음수 값이 더 작은 오렌지색 박스가 가장 아래에 위치하고, 그 위에 청록색(turquoise) 박스가 놓이는 것을 확인할 수 있습니다.

예제 2: 배경 이미지와 그림자 활용

이번에는 배경 이미지와 box-shadow를 함께 사용한 z-index 관련 스타일링 예제를 살펴보겠습니다.

<!DOCTYPE html>
<html>
<head>
<style>
p {
    background: url("https://www.tutorialspoint.com/tensorflow/images/tensorflow-mini-logo.jpg");
    background-origin: content-box;
    background-repeat: no-repeat;
    background-size: cover;
    box-shadow: 0 0 3px black;
    padding: 20px;
    background-origin: border-box;
}
</style>
</head>
<h2>Demo</h2>
<body>
<p>This is demo text. This is demo text. This is demo text. This is demo text.
This is demo text. This is demo text. This is demo text. This is demo text.
This is demo text. This is demo text. This is demo text. This is demo text.
This is demo text.</p>
</body>
</html>

실행 결과

위 코드의 실행 결과는 다음과 같습니다.

CSS z-index 속성으로 요소 겹침 제어하기

정리

z-index 속성은 position 속성(static 제외)이 설정된 요소에만 적용된다는 점을 기억하세요. 또한 요소들이 동일한 쌓임 맥락(stacking context) 안에 있을 때만 z-index 값에 따라 순서가 결정됩니다. 이 두 가지 원리만 이해하면 모달 창, 드롭다운 메뉴, 툴팁 등 다양한 겹침 레이아웃을 자유롭게 구현할 수 있습니다.