html에 쓴 태그 순으로 위치가 지정되어 순서대로 나타난다.
따로 position을 지정하지 않으면position: static
기본으로 적용된다.
<div class="box box1">box1</div>
<div class="box box2">box2</div>
.box{
color:white;
width: 100px;
height: 100px;
}
.box1{
background-color: green;
}
.box2{
position:static;
background-color: red;
}
static 자리를 기준
으로 지정한 위치만큼 움직인다.
box2의 static 자리는 위에 static 참조
static 자리를 기준으로 top에서 10만큼 떨어지고, left에서 40 만큼 왼쪽으로 떨어진다.
<div class="box box1">box1</div>
<div class="box box2">box2</div>
.box{
color:white;
width: 100px;
height: 100px;
}
.box1{
background-color: green;
}
.box2{
position: relative;
background-color: red;
left: 40px;
top: 10px;
}
조상 요소 중 기본 값 position: static을 제외한 position: relative
position: absolute
position: fixed
을 가진 가장 가까운 조상을 기준으로 지정한 위치만큼 움직인다.
모든 조상 요소가 position: static이라면 자신이 담긴 박스를 기준으로 지정한 위치만큼 움직인다.
box1-child-child는 position이 static이 아닌 가장 가까운 조상은 box1이기 때문에 box1(그린을 기준으로 왼쪽에서 100px만큼 떨어졌다.
box2-child는 모든 조상 요소가 position이 static이기 때문에 box2-child가 담긴 box2 태그를 기준으로 움직인다.
<div class="box box1">
<div class="box box1-child">
<div class="box box1-child-child">box1-child-chlid</div>
</div>
</div>
<div class="box box2">
<div class="box box2-child">box2-child</div>
</div>
.box{
color:white;
width: 100px;
height: 100px;
}
.box1{
position: relative;
background-color: green;
}
.box1-child-child {
position: absolute;
left: 100px;
background-color: violet;
}
.box2{
background-color: red;
}
.box2-child {
position: absolute;
right: 0;
background-color:black;
}
뷰포트를 기준으로 고정, 스크롤을 계속 내려도 뷰포트가 기준이 되기 때문에 쭉 그 자리를 유지한다.
box2는 자신의 부모 박스의 길이인 1000px(파란색 기준)을 넘어서도 끝까지 왼쪽에서 20px, 위에서 50px 떨어진 자리를 계속 유지하여 내려간다.
<div class="wrap">
<div class="box box1">box1</div>
<div class="box2-wrap">
<div class="box box2">box2</div>
</div>
<div class="box box3"></div>
</div>
.wrap {
height: 2000px;
}
.box{
color:white;
width: 100px;
height: 100px;
}
.box1{
background-color: red;
}
.box2-wrap {
height: 1000px;
}
.box2{
position: fixed;
left: 20px;
top: 50px;
background-color: green;
}
.box3{
top: 1000px;
background-color: cadetblue;
}
부모 박스를 기준으로 고정, 스크롤되면서 부모 박스 위치까지 같은 자리를 유지, 부모 박스가 넘어가면 사라진다.
box2는 자신의 부모 박스의 길이인 1000px(파란색 기준)을 넘어서기전까지는 위치가 고정되며 내려오다 부모 박스를 넘어가면 사라진다.
<div class="wrap">
<div class="box box1">box1</div>
<div class="box2-wrap">
<div class="box box2">box2</div>
</div>
<div class="box box3"></div>
</div>
.wrap {
height: 2000px;
}
.box{
color:white;
width: 100px;
height: 100px;
}
.box1{
background-color: red;
}
.box2-wrap {
height: 1000px;
}
.box2{
position: sticky;
left: 20px;
top: 50px;
background-color: green;
}
.box3{
top: 1000px;
background-color: cadetblue;
}