postion
속성은 레이아웃을 배치하거나, 객체를 위치를 제어할 수 있다.position
속성은 부모 요소의 postion
값을 상속받지 않는다.position
속성은 top
, bottom
, left
, right
속성과 같이 사용하여 위치를 설정할 수 있다.(단, static은 무시)position의 기본값은 static 이다.
top
,bottom
,left
,right
속성을 무시하고 가장 위 왼쪽에 위치한다.
원래 위치에서 상대적으로 위치를 변경한다.
div {
color: white;
font-size: 20px;
width: 100px;
height: 100px;
}
.box1 {
background-color: pink;
}
.box2 {
background-color: skyblue;
position: relative;
top: 0;
left: 100px;
}
.box3 {
background-color: red;
}
div
로 박스 3개를 만든후 다음과 같이 CSS를 적용하였다.
position="relative"
와left="100px"
속성에 의해 box2는 원래 자리에서 상대적으로 왼쪽에서 100px 떨어진 위치로 배치된다.
원래 위치와 상관없이 부모요소를 기준으로 위치 값이 변경된다.
부모 요소에 relative 요소가 없다면 가장 상단, 왼쪽 0, 0 값을 기준으로 위치 값이 변경된다.
위 사진과 같이 hexcode 박스를 배치하려면 position='absolute'
를 주고 그 부모요소 colorBox에 position='relative'
속성값을 부여해주면 된다.
<div class="colorBox">
<span class="hexCode">#709fb0</span>
</div>
.colorBox{
height: 370px;
border-radius: 10px;
background-color: #719fb0;
position: relative;
}
.hexCode{
color:white;
background-color: #578291;
font-size: 20px;
padding: 5px 12px;
position: absolute;
bottom: 10px;
}
원래 위치와 상관없이 브라우저 화면을 기준으로 위치를 지정할 수 있다.
상위 요소에 영향을 받지 않기 때문에 화면이 바뀌어도 고정된 위치를 설정할 수 있다.
<header>
<img src="https://www.apple.com/ac/globalnav/4/en_US/images/globalnav/apple/image_small.svg" alt="apple" width="20px" height="48px">
</header>
header{
position: fixed;
left: 0;
right: 0;
top: 0;
height: 48px;
background-color: rgba(45, 45, 45, 0.95);
}
스크롤을 내려도 헤더가 고정된 위치에 설정되어있다.
fixed
를 사용하면 inline
속성으로 바뀌기 때문에 필요에 따라서 width, height
값을 지정해야 한다.