CSS/속성 - 띄움(정렬), 위치

position 특징- 요소 쌓임 순서

appmaster 2021. 1. 12. 11:34

요소 쌓임 순서(Stack order)

요소가 쌓여있는 순서를 통해 어떤요소가 사용자와 가깝게 있는지(더 위에 쌓이는지)를 결정(Z축)

 

1. static을 제외한 position속성의 값이 있을 경우 가장 위에 쌓임(값은 무관)

2. position이 모두 존재한다면 z-index 속성의 숫자 값이 높을 수록 위에 쌓임

3. position속성의 값이 있고, z-index 속성의 숫자 값이 같다면, 'HTML'의 마지막 코드일 수록 위에 쌓임(나중에 작성한 코드(요소))

position > z-index > HTML 마지막코드

 

<div class="box-group">
  <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>

쌓여있는 모습

사진에서 보면 알 수 있듯이, 가장먼저 시작한 1번박스는 제일 밑에있고 맨뒤에있는 5번은 가장 위에 있는것을 알 수 있다. 하지만 CSS로 쌓이는 순서를 변경 할 수 있다.

 

 

<변경방법1 : position: relative>

.box-group{
  display: flex;
}
.box-group .box{
  width: 100px;
  height: 100px;
  background: tomato;
  border: 4px dashed red;
  border-radius: 10px;
  font-size: 30px;
  display: flex;
  justify-content: center;
  align-items:center;
  margin-right: -30px;
  box-shadow: 0 0 10px rgba(255, 0,0, .7);
}

.box-group .box:nth-child(2n) {
  margin-top: 30px;
}
.box1{
  
}
.box2{
  
}
.box3{
  position: relative
}
.box4{
  position: relative;
}
.box5{
  
}

4번박스에 position: relative를 넣어서 가장위에 쌓이게 할 수 있다.

가장위에 쌓여있는 4번 박스

즉, position: relative가 있으면 무조건적으로 위에 쌓이는 개념이 된다. 보기에는 3번박스와 5번박스가 같은 위치에 있는것 같지만 실제로는 3번박스가 더 위에 있다. 또한 position: relative가 선언이 중복이 된다면, html의 마지막 순서부터 위에 쌓이기 시작한다.

 

 

<변경방법2: z-index: n>

.box-group{
  display: flex;
}
.box-group .box{
  width: 100px;
  height: 100px;
  background: tomato;
  border: 4px dashed red;
  border-radius: 10px;
  font-size: 30px;
  display: flex;
  justify-content: center;
  align-items:center;
  margin-right: -30px;
  box-shadow: 0 0 10px rgba(255, 0,0, .7);
}

.box-group .box:nth-child(2n) {
  margin-top: 30px;
}
.box1{
  position: relative;
}
.box2{
  position: relative;
  z-index: 3;
}
.box3{
  position: relative;
  z-index: 1;
}
.box4{
  position: relative;
  z-index: 2;
}
.box5{
  position: relative;
}

다음과 같이 z-index: n(숫자) 로 선언할 수 있다. z-index값이 클수록 더 위쪽에 위치하게 된다.