CSS입문

CSS_position(stack order)_22.04.12(Tue)

양빵빵 2022. 4. 12. 17:27
stack order
요소 쌓임 순서(Stack order)
- 요소가 쌓여 있는 순서를 통해 어떤 요소가더 위에 쌓이는지를 결정 (Z축)
 
1. static을 제외한 position속성의 값이 있을 경우 가장 위에 쌓임
2. position이 존재한다면 z-index속성의 숫자값이 높을 수록 위에 쌓임
3. position이 존재하고 z-index속성의 숫자값이 같다면 나중에 작성한 요소일수록 위에 쌓임

 

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .container {
            width: 80%;
            margin: 50px auto 0;
        }

        .box {
            width: 100px;
            height: 100px;
            background: tomato;
            border: 4px dashed red;
            border-radius: 15px;
            font-size: 30px;
            text-align: center;
            line-height: 100px;
            float: left;
            box-shadow: 2px 2px 20px #222;
            margin-right: -30px;
            position: relative;
        }

        .box:nth-child(even) {
            margin-top: 30px;
        }

        .box1 {
            z-index: 100;
        }

        .box2 {
            z-index: 1;
        }

        .box3 {
            z-index: -1;
        }

        .box4 {
            z-index: 0;
        }

        .box5 {
            z-index: 0;
        }

        /* 우선순위 position 이 없을때 html에서 가장 나중에 작성된 요소가 가장 위에 쌓임
        position이 하나의 요소에만 있을때 그 요소가 가장 위에 쌓임.
        position이 두개 이상의 요소에 있을 때 html에서 가장 나중에 작성된 요소가 가장 위에 쌓임.
        모든 요소에 position이 있을 때 z-index 의 속성값이 높은 요소가 가장 위에 쌓임.
        모든 요소에 position이 있고 z-index 의 속성값이 같을때 html에서 가장 나중에 작성된 요소가 위에 쌓임..
                 */
    </style>
</head>

<body>
    <div class="container">
        <div class="box box1">1</div>
        <div class="box box2">2</div>
        <div class="box box3">3</div>
        <div class="box box4">4</div>
        <div class="box box5">5</div>
    </div>
</body>

</html>