Style Sheet/CSS

CSS position

conqueror-G 2022. 5. 24. 20:49

position 속성 사용하는 이유 

HTML의 어떤 요소를 배치할 때 사용한다.

position property

property description precautions
static default 값이다. z-index 속성이 아무 영향도 주지 않는다.
relative 자기 자신을 기준으로 한다. 형제 요소가 사라지면 형제요소의 너비 만큼 재배치된다.
absolute position property가 적용된 대상을 기준으로 한다. 단) static은 제외한다. 상위 요소에 position이 적용이 되지 않았다면 뷰포트를 기준으로 한다.
fixed 해당 property가 적용되면 element가 문서 상의 순서에서 제거되고 자기 자신이 있는 자리에서 고정된다.  상위 요소가 아니라 브라우저를 기준으로 한다.

공통 코드

<div class="parent">
  <div class="child common">1</div>
  <div class="child common">2</div>
  <div class="child common">3</div>
</div>
.parent {  // 스크롤을 주기 위해 2000px을 부여했다.
  height: 2000px;
  /* position: relative */
  /* 하위 요소에 absolute를 사용할 때 적용해야한다 */
}

.common {  // 공통 스타일 적용이라 볼 필요 없다.
  width: 200px;
  height: 200px;
  font-size: 3rem;
  display: flex;
  justify-content: center;
  align-items: center;
}

.parent div:nth-child(1) {
  background-color: green;
}

.parent div:nth-child(2) {
  background-color: aqua;
  /*   position: relative; */
  /*   position: absolute; */
  /* position absolute를 사용할 경우 기준점으로 하려는 셀렉터에
  position relative를 적용해야한다.*/
  /*   position: fixed; */
}

.parent div:nth-child(3) {
  background-color: blue;
}

 

relative

자기 자신을 기준으로 배치한다.

absolute

position: relative가 적용된 element를 기준으로 한다. 다만 absolute가 적용되는 순간 밀려난 자식처

럼 취급받게 된다.

-> top, bottom, left, right 값이 auto가 된다.
밑의 그림은 없는 자식이 된 2번 박스가 보이도록 right 0을 줬다.

fixed

없는 자식이 되는 것은 매한가지! absolute와 다른점으로는 부모 요소가 필요 없으며 뷰포트에 고정이된다.

네이버 웹툰에서 정주행할 때 오른쪽 하단에 따라다니는 버튼이라고 생각하면 된다. 스크롤을 하더라도 뷰포트에 고정됬기 때문에 뷰포트의 이동에 따라 같이 이동하는 것처럼 보인다.