본문 바로가기
프론트엔드/CSS

요소의 배치

by step 1 2021. 4. 25.
반응형

position: 요소의 위치 지정 기준 (기준 -> 위치)

  • static: 기준 없음(기본값)
  • relative: 요소 자신을 기준(실제로 거의 사용되지 않음)
  • absolute: 위치 상 부모 요소를 기준
  • fixed: 뷰포트(브라우저)를 기준
  • sticky: 스크롤 영역 기준

top, bottom, left, right: 요소의 각 방향별 거리 지정

  • auto: 브라우저가 계산(기본값)
  • 단위: px, em, rem등 단위로 지정
<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
</div>
.container .item:nth-child(2){
  width: 140px;
  height: 100px;
  position: relative;
  top: 30px;
  left: 200px;
}

relative 결과

.container {
  width: 300px;
  background-color: royalblue;
  position: relative;
}
.container .item:nth-child(2){
  width: 140px;
  height: 100px;
  position: absolute;
  bottom:30px;
  right: 60px;
}

absolute 결과

.container .item:nth-child(2){
  width: 140px;
  height: 100px;
  position: fixed;
  bottom:30px;
  right: 60px;
}

fixed 결과(스크롤을 내려도 항상 그 위치에 고정)

 

요소 쌓임 순서(Stack order): 어떤 요소가 사용자와 더 가깝게 있는지(위에 쌓이는지) 결정

1. 요소에 position 속성의 값이 있는 경우 위에 쌓임(기본값 static 제외)

2. 1번 조건이 같은 경우, z-index 속성의 숫자 값이 높을 수록 위에 쌓임

3. 1번과 2번 조건까지 같은 경우, HTML의 다음 구조일 수록 위에 쌓임

 

.container .item:nth-child(1){
  width: 100px;
  height: 100px;
  position: relative;
  z-index: 1;
}
.container .item:nth-child(2){
  width: 140px;
  height: 100px;
  position: absolute;
  top: 50px;
  left:50px;
}
.container .item:nth-child(3){
  width: 70px;
  height: 120px;
  z-index: 9999;

결과

z-index: 요소의 쌓임 정도를 지정

auto: 부모 요소와 동일한 쌓임 정도

숫자: 숫자가 높을 수록 위에 쌓임

 

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

<span>123</span>
span {
  width: 100px;
  height: 100px;
  background-color: orange;
  font-size: 40px;
  position: absolute;
}

결과

 

반응형

'프론트엔드 > CSS' 카테고리의 다른 글

전환 효과  (0) 2021.04.28
요소의 정렬(플렉스)  (0) 2021.04.26
배경 속성  (0) 2021.04.22
문자와 관련된 속성  (0) 2021.04.22
CSS 넘침 제어  (0) 2021.04.18