position은 문서 상에 요소를 배치하는 방법을 정의한다.
position이 요소의 배치 방법을 결정하면 top, bottom, right, left가 최종 위치를 결정하는 방식이다.
static : 기본값, 요소를 일반적인 문서 흐름에 따라 배치한다.
relative : 일반적인 문서 흐름에 따라 배치하되, 상하좌우 위치 값에 따라 오프셋을 적용한다.
absolute : 일반적인 문서 흐름에서 제거하고 가장 가까운 position 지정 요소에 대해 상대적으로 오프셋을 적용한다.
fixed : 일반적인 문서 흐름에서 제거하고 지정한 위치에 고정된다.
sticky : 일반적인 문서 흐름에서 제거하고 스크롤이 동작하는 존재에서 가장 가까운 요소에 대해 오프셋을 적용한다.
요소를 일반적인 문서 흐름에 따라 배치하되 상하좌우 위치 값에 따라 오프셋을 적용한다.
[style.css]
div{
width: 100px;
height: 100px;
background-color: red;
position:relative;
top: 100px;
left: 100px
}
[index.html]
<body>
<div>
가나다라마바사
</div>
</body>
요소를 일반적인 문서 흐름에서 제거하고, 상위 요소 중 가장 가까운 position 지정 요소에 대해 상대적으로 오프셋을 적용한다.
[style.css]
div{
width: 200px;
height: 200px;
background-color: red;
position:relative;
border: black 1px solid
}
.abs{
width:100px;
height: 100px;
position: absolute;
top: 100px;
background-color: yellow;
}
[index.html]
<body>
<div>
가나다라마바사
</div>
<div>
<div class="abs"></div>
</div>
</body>
요소를 일반적인 문서 흐름에서 제거하고, 지정된 위치에 고정시킨다.
[style.css]
.box{
width: 50px;
height: 50px;
background-color: red;
position: fixed;
top: 50px;
}
[index.html]
<body>
<div>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
<div class="box">
</div>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
</div>
</body>
요소를 일반적인 문서 흐름에 따라 배치하고, 스크롤되는 가장 가까운 상위 요소에 대해 오프셋을 적용한다.
[style.css]
.box{
width: 50px;
height: 50px;
background-color: red;
position: sticky;
top: 50px;
}
[index.html]
<body>
<div>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
<div class="box">
</div>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
가나다라마바사</br>
...스크롤이 생길 때 까지
스크롤을 내리면 상자가 함께 내려오며 스크롤이 원래위치로 돌아가면 상자도 원래 위치로 돌아간다.