[CSS] #2. z-index

Jihye·2024년 1월 3일
0

CSS

목록 보기
2/6
post-thumbnail

요소 쌓임 순서(Stack order)

z-index

어떤 요소가 사용자와 더 가깝게 있는지(위에 쌓이는지) 결정

  • auto :부모 요소와 동일한 쌓임 정도
  • 숫자 : 숫자가 높을 수록 위에 쌓임
  • 이때, 기본값 static은 고정된 요소이기 때문에 아무리 수가 높아도 쌓임이 우선되지 않는다. 즉, static에는 z-index 아무 소용 없다!

실습. 애벌레 만들기

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>실습2</title>
    <link rel="stylesheet" href="practice2.css">
</head>
<body>
    <div class="main">
        <div class="body b1"></div>
        <div class="body b2"></div>
        <div class="body b3"></div>
        <div class="body b4"></div>
        <div class="body b5"></div>
        <div class="face f1"></div>
        <div class="face f2"></div>
    </div>
    <img class="grass" src="grass.png" alt="grass">
    
</body>
</html>

CSS

.main{
    position: relative;
}
.body{
    border-radius: 50%;
    width: 100px;
    height: 100px;
    position: absolute;
}
.b1{
    background-color: rgba(35, 106, 228, 0.879);
    z-index: 1;
    
}
.b2{
    background-color: rgb(0, 0, 255);
    top: 30px;
    left: 70px;
    z-index: 2;
}
.b3{
    background-color: rgb(0, 179, 255);
    top: 70px;
    left:100px;
    z-index: 3;
    
}
.b4{
    background-color: skyblue;
    top: 65px;
    left: 150px;
    z-index: 4;
}
.b5{
    background-color: rgb(0, 128, 117);
    top: 63px;
    left: 210px;
    z-index: 600;
}
.face{
    border-radius: 50%;
    position: absolute;
}
.f1{
    width: 30px;
    height: 30px;
    background-color: white;
    top: 20px;
    left: 20px;
    z-index: 100;
}
.f2{
    width: 20px;
    height: 20px;
    background-color: black;
    top: 22px;
    left: 20px;
    z-index: 200;
}
.grass{
    position: absolute;
    top: 90px;
    z-index: 300;
}

결과

중요한 점!

  • 모든 요소를 main class안에 넣고, main은 relative, 나머지는 absolute로 선언하여 위치를 잡을 수 있다.
  • z-index의 정수값이 클수록 더 높이 쌓인다.
  • z-index는 한 부모 요소안에 있는 자식 요소들끼리의 쌓임 정도를 결정하는 것!

0개의 댓글