position 속성 : relative, absolute, fixed

Moolbum·2021년 11월 3일
0

css

목록 보기
2/3
post-thumbnail

position

position : ( relative, absolute, fixed )

position 의 종류

absolute: 절대 좌표와 함께 위치를 지정해 줄 수 있습니다.
relative: 원래 있던 위치를 기준으로 좌표를 지정합니다.
fixed: 스크롤과 상관없이 위치가 고정되어있다.
static: 기본값, 자동으로 배치, 위치를 임의로 설정해 줄 수 없습니다.
inherit: 부모 태그의 속성값을 상속받습니다.

relative, absolute, fixed는 단일로서는 사용 할 수 없다.
좌표를 지정하기 위해 left, right, top, bottom 속성을 사용해야 한다.

position:relative;
left: 0;
top: 40px;

relative , absolute의 사용법

부모 요소에 relative 속성을 부여하고, 자식 요소에 absolute 속성을 부여하면 부모의 relative의 상속되어 absolute는 relative 내부를 기준으로 움직인다.

위치부여를 하지 않을 때

.relative {
  width:200px;
  height:150px;
  position:relative;
  border:1px solid green;
}
.absolute {
  position:absolute;
  border:1px solid red;
}

위치부여를 주었을 때
top, right, left, bottom 4가지 속성으로 위치를 조정 할 수 있다.

.relative {
  width:200px;
  height:150px;
  position:relative;
  border:1px solid green;
}
.absolute {
  position:absolute;
  border:1px solid red;
  left:30px;
}

fixed의 사용법

fixed를 사용하면 스크롤을 이동해도 항상 화면 최상단에 위치해있는다. 다른 position 효과처럼 좌표를 지정하기 위해 left, right, top, bottom 속성을 사용해야 한다.

<div class="fixed">fixed</div>
<div class="box">1<div>
<div class="box">2</div>
  
.fixed {
  position:fixed;
  width:100px;
  heigth:50px;
  background-color:gray;
  margin:0 auto;
  left:0;
  top:0;
}
.box {
  width:100px;
  heigth:100px;
  background-color:red;
}

1번 박스를 보여주고 싶다면 css에서 body태그에서 padding-top 값을 주면 된다.

body {
  padding-top:20px;
}

이렇게 fixed는 뒤에있는 요소들을 무시하고 화면 최상단에 보여준다. fixed를 사용하면 사용자가 어느 위치에서 스크롤을해도 내비게이션이 노출되기에 접근성이 용이하다.

ex) 애플

profile
Junior Front-End Developer 👨‍💻

0개의 댓글