본문 바로가기
🔗 HTML & CSS

CSS Layout - Position

by 슬용이 2022. 4. 26.

Position

Position 속성은 요소의 위치 지정 방법(static, relative, fixed, absolute, sticky)을 지정한다.

지정 후에는 top, bottom, left, right 속성을 통해 배치할 수 있으며, 지정 된 속성에 따라 해당 값들은 다르게 작동한다.

 


(1) static

HTML의 요소들은 static이 기본으로 배치되어 있다.

position: static; 으로 지정 된 값들은 딱히 특별한 기능을 하지 않으며, 페이지에 의한 기본적인 흐름에 따라 배치된다.

div.static {
  position: static;
  border: 3px solid #73AD21;
}

평범한 박스이다.


(2) relative

position: relative;로 지정 된 요소는 기존의 위치를 기준으로 상대적인 위치를 지정할 수 있다.

top, bottom, left, right 속성을 설정하면 해당 거리만큼 멀어지게 된다. 다른 콘텐츠들은 간격에 맞게 조정되지 않으니 주의하자.

div.relative {
  position: relative;
  left: 30px;
  border: 3px solid #73AD21;
}

오른쪽으로 뚫고 가버린 박스...


(3) fixed

position: fixed;로 지정 된 요소는 뷰포트에서 상대적으로 위치하는데,

페이지를 스크롤하거나 크기를 조절해도 항상 그 자리에 머물러있다는 의미이다.

top, bottom, left, right 속성은 이 위치를 지정하는데 사용되며, 페이지에 Gap을 남기지 않는 특징이 있다.

div.fixed {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 300px;
  border: 3px solid #73AD21;
}

창 크기를 조정해도 계속 하단 모서리에 고정되어 있는 fixed;


(4) absolute

position: absolute;로 지정 된 요소는 가장 가까운 위치의 부모 요소를 기준으로 배치된다.

하지만, 부모 요소가 없다면 문서 본문을 기준으로 이동되며, 일반적인 흐름에서 벗어나 다른 요소와 겹치기도 한다.

div.relative {
  position: relative;
  width: 400px;
  height: 200px;
  border: 3px solid #73AD21;
}

div.absolute {
  position: absolute;
  top: 80px;
  right: 0;
  width: 200px;
  height: 100px;
  border: 3px solid #73AD21;
}

부모 태그를 기준으로 위치된 작은 박스


(5) sticky

position: relative;로 지정 된 요소는 사용자의 스크롤 위치를 기준으로 배치된다.

스크롤 위치에 따라 relativefixed 기능을 전환하는데,

주어진 offset 위치가 뷰포트에서 만날 때 까지(스크롤이 필요없을 때 까지)는 해당 위치에 fixed 되는 형식이다.

Note: 
Internet Explorer does not support sticky positioning. Safari requires a -webkit- prefix (see example below). You must also specify at least one of top, right, bottom or left for sticky positioning to work.
div.sticky {
  position: -webkit-sticky; /* Safari */
  position: sticky;
  top: 0;
  background-color: green;
  border: 2px solid #4CAF50;
}

스크롤을 해도 상단에 붙여서 고정되어 있는 걸 볼 수 있다.

 

 

'🔗 HTML & CSS' 카테고리의 다른 글

Display Property : inline, block, inline-block  (0) 2022.04.26
About Semantic  (0) 2022.04.26
display:none 과 visibility:hidden 의 차이  (0) 2022.01.28
CodeAcademy - HTML Table  (0) 2022.01.12
생활코딩 WEB2 - CSS (3)  (0) 2022.01.11

댓글