[HTML & CSS] CSS에서 position: absolute와 position: relative의 관계





1. position: absolute란?

CSS에서 position: absolute를 적용하면 해당 요소는 문서 흐름에서 제거되며, 특정 기준점을 기준으로 배치됩니다.
이때 기준점이 되는 요소는 가장 가까운 position이 지정된(즉, relative, absolute, fixed 중 하나인) 부모 요소입니다.


만약 부모 요소가 position: static(기본값)이라면, absolute 요소는 <html> 요소(즉, 문서 전체)를 기준으로 배치됩니다.


.parent {
  width: 300px;
  height: 300px;
  background-color: lightblue;
}

.child {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 100px;
  height: 100px;
  background-color: red;
}


<div class="parent">
  <div class="child"></div>
</div>

이 경우 .child 요소는 문서 전체를 기준으로 top: 50px, left: 50px 위치에 배치됩니다.



2. 부모 요소에 position: relative를 설정하는 이유

부모 요소에 position: relative를 설정하면, 해당 부모가 자식 요소의 기준점이 됩니다.
즉, absolute 요소는 문서가 아닌 부모 요소를 기준으로 배치됩니다.


.parent {
  position: relative; /* 부모 요소를 기준점으로 만듦 */
  width: 300px;
  height: 300px;
  background-color: lightblue;
}

.child {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 100px;
  height: 100px;
  background-color: red;
}


<div class="parent">
  <div class="child"></div>
</div>

이제 .child 요소는 .parent 요소를 기준으로 top: 50px, left: 50px 위치에 배치됩니다.


부모에 relative가 없으면?

부모 요소가 position: static이면 .child 요소는 <html>을 기준으로 배치됩니다. 따라서 원하는 위치에 정확히 배치하려면 부모 요소에 position: relative를 추가해야 합니다.



3. position: absolute와 position: relative의 관계 정리

자식 요소
(position: absolute)
부모 요소
(position)
기준점
absolutestatic (기본값)<html>(문서 전체)
absoluterelative부모 요소
absoluteabsolute부모 요소
absolutefixed뷰포트(화면)

즉, 부모에 relative를 주면 absolute 요소가 해당 부모를 기준으로 배치되는 것이 핵심입니다.



4. absolute 사용 시 주의할 점




4-1. 부모 요소에 height가 없을 때

부모 요소가 position: relative지만 height를 지정하지 않으면, 내부 absolute 요소가 부모의 크기를 결정하지 않으므로 의도한 대로 배치되지 않을 수 있습니다.


.parent {
  position: relative;
  background-color: lightblue;
}

.child {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 100px;
  height: 100px;
  background-color: red;
}


<div class="parent">
  <div class="child"></div>
</div>

이 경우 .parent 요소에 height가 지정되지 않으면, .child가 의도한 대로 배치되지 않을 수 있습니다.


해결 방법: 부모 요소에 height 값을 명시적으로 설정하거나, 내부 요소들의 높이를 기반으로 자동으로 설정되도록 해야 합니다.



5. absolute와 relative를 활용한 예제




5-1. 우측 하단에 버튼 고정하기

.container {
  position: relative;
  width: 300px;
  height: 300px;
  background-color: lightgray;
}

.button {
  position: absolute;
  bottom: 10px;
  right: 10px;
  padding: 10px;
  background-color: blue;
  color: white;
}


<div class="container">
  <button class="button">버튼</button>
</div>

.button 요소가 .container 요소의 오른쪽 하단에 배치됩니다.



6. 결론

  • position: absolute부모 요소가 position: relative 이상일 때 해당 부모를 기준으로 배치됩니다.
  • 부모에 position: relative가 없으면 문서 전체(<html>)를 기준으로 배치됩니다.
  • 특정 요소를 부모 기준으로 배치하려면 부모에 position: relative를 추가해야 합니다.
  • absolute 요소는 문서 흐름에서 제거되므로 부모의 크기에 영향을 주지 않습니다.



댓글 남기기