[CSS] position (static, relative, absolute, fixed, sticky)

position

요소를 배치할 기준점을 정하는 속성이다!

 

static

HTML 요소의 기본 위치이다. position: static인 요소는 top, bottom, right, left를 지정해줘도 이동하지 않고 원래 위치에 배치된다.

 

relative

요소의 기본 위치를 기준으로 설정된 값만큼 top, bottom, right, left 방향 이동한다.

position: relative;
top: 50px;
left: -100px;

 

왼쪽이 위치를 설정하지 않은 기본 상태, 오른쪽이 위 코드를 적용한 상태이다.

top 에서부터 +50px만큼 좌표가 이동하고 left에서부터 -100px만큼 이동한 것을 볼 수 있다.

 

 

absolute

부모 요소 중 가장 가까운 relative 요소를 기준으로 이동한다.

이미지 위의 특정 위치에 버튼을 올리고 싶을 때 사용한 적이 있다.

 

.relative-element {
    width: 300px;
    height: 200px;
    margin: 100px;
    background-color: lightseagreen;
    position: relative;
}
.absolute-element {
    width: 50px;
    height: 50px;
    background-color: bisque;
    position: absolute;
    bottom: 50px;
    right: 50px;
}

 

부모요소의 bottom에서부터 50px, right에서부터 50px 이동한 위치에 배치된다.

 

 

fixed

화면(뷰포트)를 기준으로 이동한다.

따라서 다른 요소들의 이동에 상관없이 화면에 고정된 요소를 만들어야할 때 사용할 수 있다!

(상단 고정 메뉴, 맨위/맨아래로 이동 버튼 등)

 

div {
    background-color: lightseagreen;
    width: 400px;
    height: 100px;
    border: 1px solid lightgrey;
}
.fixed-element {
    position: fixed;
    top: 3px;
    background-color: lightpink;
}

 

화면 기준 top에서부터 3px 위치에 고정시켜두었다.

 

 

sticky

첫 렌더링 시 문서흐름상의 위치에 있다가, 뷰포트 기준 지정한 위치에 도달하면 요소가 고정된다.

특정 위치에서 브라우저 스크롤에 상관없이 고정되어 따라다니기를 원할 때 사용할 수 있다.

스크롤되면서 부모 요소의 반대쪽 끝과 만났을 때 다시 고정해제된다.

 

.container {
    background-color: lightgrey;
    width: 500px;
    height: 300px;
}
.sticky-element {
    position: sticky;
    top: 100px;
    width: 100px;
    height: 50px;
    background-color: violet;
}

 

sticky가 적용되지 않을 때

1) 부모태그에 height가 있어야 함!

2) 부모 요소에 overflow: hidden, auto, scroll 속성이 적용돼있으면 안됨

3) sticky 요소에 top, bottom, right, left 위치값 설정하기 (최소 하나)