HTML_CSS
HTML5 CSS: position 속성, static relative absolute sticky
고니자니
2025. 5. 20. 12:08
반응형
CSS에서 position 속성은 요소의 위치를 어떻게 배치할지를 정의하는 데 사용됩니다. position에는 다섯 가지 주요 값이 있으며, 각각의 동작 방식이 다릅니다.
1. static (기본값)
- 요소는 문서의 흐름에 따라 배치됩니다.
- top, left, right, bottom은 무시됩니다.
<div style="position: static; top: 10px;">Static Position</div> |
➡️ top: 10px는 무시됩니다.
2. relative
- 요소는 자신의 원래 위치를 기준으로 이동합니다.
- 문서 흐름에서는 원래의 위치를 유지한 채 보이는 위치만 이동합니다.
<div style="position: relative; top: 20px; left: 30px;">Relative Position</div> |
➡️ 위쪽으로 20px, 왼쪽으로 30px 이동하지만 원래 자리의 공간은 그대로 유지됩니다.
3. absolute
- 요소는 가장 가까운 position: relative, absolute, fixed, sticky 조상 요소를 기준으로 위치가 결정됩니다.
- 해당 조상이 없으면 <html>을 기준으로 위치합니다.
<div style="position: relative;"> <div style="position: absolute; top: 10px; left: 10px;">Absolute Position</div> </div> |
➡️ 부모가 relative이므로 그 부모를 기준으로 top: 10px, left: 10px 위치에 배치됩니다.
4. fixed
- 브라우저 창을 기준으로 위치합니다. (스크롤해도 고정됨)
- 항상 같은 위치에 표시됩니다.
<div style="position: fixed; bottom: 10px; right: 10px;">Fixed Position</div> |
➡️ 브라우저 오른쪽 아래에 고정됩니다.
5. sticky
- 스크롤 위치에 따라 relative와 fixed 사이에서 동작합니다.
- 특정 위치에 도달하면 고정됩니다.
html
복사편집
<div style="position: sticky; top: 0; background: yellow;">Sticky Position</div>
➡️ 이 요소는 스크롤할 때 top: 0 지점에서 고정됩니다.
예제
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 150px;
height: 100px;
background: lightblue;
margin: 20px;
}
.relative {
position: relative;
top: 20px;
left: 30px;
}
.absolute-container {
position: relative;
height: 200px;
background: lightgray;
}
.absolute {
position: absolute;
top: 10px;
right: 10px;
background: coral;
}
.fixed {
position: fixed;
bottom: 0;
right: 0;
background: lightgreen;
}
.sticky {
position: sticky;
top: 0;
background: gold;
}
</style>
</head>
<body>
<div class="box relative">Relative</div>
<div class="absolute-container">
<div class="box absolute">Absolute</div>
</div>
<div class="box fixed">Fixed</div>
<div class="box sticky">Sticky (Scroll to see)</div>
</body>
반응형