CSS 레이아웃 - position

sanha_OvO·2021년 11월 2일
0

Frontend

목록 보기
3/7

position

CSS에선 position 속성을 통해 해당 요소를 HTML에서 어떻게 배치할 지 결정할 수 있다.

이 글에서 position의 프로퍼티들을 알아보자.

static

staticposition의 기본값이다.
top, bottom, left, right속성에 영향을 받지 않으며 HTML에 작성된 흐름에 따라 배치가 결정된다.

<div>
  HI
</div>
<div>
  HI
</div>
<div>
  HI
</div>
div {
  width: 100px;
  height: 100px;

  border: 3px solid red;
}

relative

relativeposition: static; 일 때 배치되는 위치를 기준으로 요소를 움직이게 된다.

<div>
  HI
</div>
<div>
  HI
</div>
<div class="relative">
  HI
</div>
div {
  width: 100px;
  height: 100px;

  border: 3px solid red;
}

.relative {
  position: relative;
  top: 20px;
  left: 30px;
}

absolute

absoluterelative, fixed, absolute속성을 가진 부모를 가질 때, 해당 부모를 기준으로 절대적인 위치에 고정된다.

<div class="container">
  <div class="absolute">
    HI
  </div>
</div>
.absolute {
  position: absolute;

  width: 100px;
  height: 100px;

  top: 100px;
  left: 150px;

  border: 3px solid red;
}

.container {
  position: relative;

  width: 200px;
  height: 300px;

  top: 50px;
  left: 50px;

  border: 3px solid blue;
}

fixed

fixed뷰포트(viewport)를 기준으로 위치가 결정된다. 즉, 사용자가 보고있는 브라우저 화면을 기준으로 요소가 고정된다.

<div class="fix">
  hi
</div>
<div class="non-fix"></div>
.non-fix {
  width: 100px;
  height: 10000px;

  top: 100px;
  left: 50%;

  border: 3px solid red;
}

.fix {
  position: fixed;

  width: 200px;
  height: 300px;

  top: 100px;
  left: 50%;

  border: 3px solid blue;
}

예제 화면을 보면 스크롤을 내려도 파란박스가 고정되어있는 걸 볼 수 있다.

profile
Web Developer / Composer

0개의 댓글