HTML 요소를 배치하는 방법을 지정합니다.
요소가 HTML 문서에서 일반적인 흐름을 따라서 배치됩니다.
Inline Element
: 좌 -> 우
Block Element
: 위 -> 아래
main
section
article
div
태그는 position
의 속성이 static
입니다.
top
right
bottom
left
는 비활성화 되어 있습니다.
요소가 HTML 문서에서 일반적인 흐름을 따라서 배치됩니다.
요소가 자신의 static
위치에서 top
right
bottom
left
와 같은 속성에 의한 상대적인 위치에 배치되는 static
과의 차이점입니다.
요소가 문서의 일반적인 흐름을 따르지 않습니다.
position: static;
속성을 가지고 있지 않은 부모를 기준으로 움직입니다.
만약 부모 중에 포지션이 relative
absolute
fixed
태그가 없다면 가장 위의 태그인 body
가 기준이 됩니다.
요소가 문서의 일반적인 흐름을 따르지 않습니다.
대신 스크린의 viewport를 기준으로 한 위치에 배치됩니다.
즉, 스크롤이 되어도 움직이지 않는 고정된 자리를 가지게 됩니다.
🧐 viewport란? 웹 브라우저가 브라우저 화면 상에서 실제로 표시되는 영역
요소가 HTML 문서 안에서 일반적인 흐름을 따라 가다가 스크롤 위치가 임계점에 이르면 fixed
와 같이 박스를 화면에 고정할 수 있는 속성입니다.
top
속성을 적용해야 스크롤 임계점에서 고정이 됩니다.
left
right
bottom
속성은 사용할 수 없습니다.
✍ 코드
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
main, section, article, div {
border: 1px solid black;
padding: 20px;
}
main {
max-width: 600px;
margin: 0 auto;
background-color: yellow;
}
section {
background-color: violet;
}
article {
background-color: cyan;
}
div {
background-color: white;
}
div.relative {
position: relative;
right: 20px;
}
div.absolute {
position: absolute;
background-color: grey;
top: 0px;
left: 0px;
}
div.fixed {
position: fixed;
background-color: red;
top: 30px;
right: 300px;
border-radius: 50%
}
div.sticky {
position: sticky;
top: 0px;
}
</style>
</head>
<body>
<main>
main
<section>
section
<article>
article
<div>static</div>
<div class="relative">relative</div>
<div class="absolute">absolute</div>
<div class="fixed">fixed</div>
<div class="sticky">sticky</div>
</article>
</section>
</main>
</body>
👉 결과
어느 HTML 요소가 앞으로 나올지 뒤에 있을지 배치 순서를 결정하는 속성입니다.
position이 relative
absolute
fixed
에만 작동합니다.
z-index: 숫자;
에서 숫자가 높을수록 앞에 배치됩니다.
✍ 코드
<head>
<style>
div.relative {
position: relative;
top: -100px;
z-index: 5;
}
</style>
</head>
<body>
<div class="relative">relative</div>
</body>