Ch 8. CSS 속성- 배치: 요소 쌓임 순서

요소 쌓임 순서(Stack order)

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

  1. 요소가 position 속성의 값이있는 경우 위에 쌓임. (기본값 static 제외)
  2. 1번 조건이 같은 경우, z-index 속성의 숫자 값이 높을 수록 위에 쌓임
  3. 1번과 2번 조건 같은 경우, HTML의 다음 구조일 수록 위에 쌓임
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
.container {
  width: 300px;
  background-color: royalblue;
  position: relative;
}

.container .item {
  border: 4px dashed red;
  background-color: orange;
  width: 100px;
  height: 100px;
}

.container .item:nth-child(1) {
  position: relative;
}

**.container .item:nth-child(2) {
  position: absolute;
  top: 50px;
  left: 50px;
}
** .container .item:nth-child(3) {
}

1번,2번 item: 1번 조건 충족

2번 item: 3번 조건 충족

2 > 1 > 3

z-index

요소의 쌓임 정도를 지정

  • auto: 부모 요소와 동일한 쌓임 요소
  • 숫자: 숫자가 높을 수록 위에 쌓임


image

부모(파랑):position: relative, z-index: 0(auto)
자식 1(노랑): position: static ⇒ z-index를 주는 의미가 없다.
자식 2(주황): position: absolute, z-index: 1
자식 3: position: absolute, z-index: 2

주의

position 속성의 값으로 absolute, fixed가 지정된 요소는 display 속성이 block으로 변경

1
<span>123</span>
1
2
3
4
5
6
7
span {
  width: 100px;
  height: 100px;
  background: orange;
  font-size: 40px;
  /*position: absolute;*/
}

span요소

absolute 적용