본문 바로가기
html & css & js 공부

css: css에서 레이어처럼 겹치는 순서 조정하기

by 두 그루 2023. 1. 14.

html에서 position 속성(absolute, relative, fixed 등)을 이용하여 포토샵의 레이어처럼 겹쳐서 나타낼 수 있다.

 

가끔 추가로 겹치는 순서를 조정하여 표현해야 할 때가 있다. 그럴 때는 z-index를 이용하면 된다. z-index에 정수를 넣어줌으로써 레이어의 순서를 조정하듯이 설정할 수 있다. 정수의 값이 클수록 가장 위에 표현된다.

 

아래 예시를 참고하면 된다.

우선 이렇게 z-index는 설정하지 않고 position으로만 겹친 rainbow를 만들었다.

 

html 파일

<!DOCTYPE html>
<html>
  <head>
    <title>Rainbow</title>
    <meta chrset="utf-8" />
    <meta name="description" content="website that exisit in my local" />
    <link href="style.css" rel="stylesheet" />
  </head>
  <body>
    <div class="rainbow">
      <div class="rainbow__color"></div>
      <div class="rainbow__color"></div>
      <div class="rainbow__color"></div>
      <div class="rainbow__color"></div>
    </div>
  </body>
</html>

css 파일

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    width: 100vw;
}

.rainbow {
    display: flex;
    flex-direction: column;
    position: relative;
}

.rainbow__color {
    height: 100px;
    width: 300px;
    border-radius: 50px;
    box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.3);
    position: absolute;
}

.rainbow__color:nth-child(1) {
    background-color: rgb(255, 154, 154, 0.9);
    top: -140px;
    left: -150px;
}

.rainbow__color:nth-child(2) {
    background-color: rgba(255, 247, 154, 0.9);
    top: -70px;
    left: -150px;
}

.rainbow__color:nth-child(3) {
    background-color: rgba(154, 255, 228, 0.9);
    top: 0px;
    left: -150px;
}

.rainbow__color:nth-child(4) {
    background-color: rgba(161, 154, 255, 0.9);
    top: 70px;
    left: -150px;
}

 

아래의 사진과 같이 코드 순서가 아닌, 임의의 순서대로 표현할 수 있다.

z-index 값

- 분홍색: 3

- 노랑색: 2

- 민트색: 1

- 파랑색: 0

숫자의 값으로 표현하기 때문에 꼭 연속적인 값이 아니어도 된다. 위의 사진은 아래의 코드를 적용한 예다.

/* 다른 값들은 첫 번째 css 파일과 동일 */

.rainbow__color:nth-child(1) {
    z-index: 1;
}

.rainbow__color:nth-child(2) {
    z-index: 100;
}

.rainbow__color:nth-child(3) {
    z-index: 9;
}

.rainbow__color:nth-child(4) {
    z-index: 5;
}

댓글