position: relative
와 position: absolute
의 차이와 관계성에 대해 알아보자
우선 2개의 박스를 준비한다.
position: relative
는 자신이 원래 있었던 위치를 기준으로 이동한다.
.box1 {
position: relative;
top: 50px;
left: 50px;
width: 200px;
height: 200px;
background: #ccc;
}
.box2 {
position: relative;
left: 100px;
width: 100px;
height: 100px;
background: #33d9b2;
}
➡️ box1은 자신이 원래 있었던 위치에서 top:50px
, left:50px
만큼 움직였고,
box2 또한 자신이 원래 있었던 위치에서 left:100px
만큼 움직였다.
position: absolute
는 relative
속성을 가진 부모의 위치 기준으로 움직인다.
<style>
.box1 {
position: absolute;
top: 50px;
left: 50px;
width: 200px;
height: 200px;
background: #ccc;
}
.box2 {
position: absolute;
left: 100px;
width: 100px;
height: 100px;
background: #33d9b2;
}
</style>
<body>
<div class="box1">box1</div>
<div class="box2">box2</div>
</body>
➡️ 하지만 위 코드에서는 relative
속성이 적용된 부모가 없으므로 상위 태그인 body
를 기준으로 이동한다.
absolute
를 relative
기준으로 이동시키려면 relative
속성이 적용된 부모 아래에 있어야 한다. 즉, box2
를 box1
에 넣어주어야 한다. 하지만 아래와 같이 div가 동등한 형제 관계로 있다면 어떻게 될까?
<style>
.box1 {
position: relative;
top: 50px;
left: 50px;
width: 200px;
height: 200px;
background: #ccc;
}
.box2 {
position: absolute;
top: 0;
left: 100px;
width: 100px;
height: 100px;
background: #33d9b2;
}
</style>
<body>
<div class="box1">box1</div>
<div class="box2">box2</div>
</body>
➡️ absolute
는 relative
기준으로 움직이지 않는다. 두 박스에 동일한 속성 absolute
를 주었을 때와 똑같이 이동한다. box2
는 box1
이 아닌 body
기준으로 움직이기 때문이다.
absolute
를 relative
기준으로 이동시키기 위해 box2를 box1에 넣어주었다.
<style>
.box1 {
position: relative;
top: 50px;
left: 50px;
width: 200px;
height: 200px;
background: #ccc;
}
.box2 {
position: absolute;
top: 0;
left: 100px;
width: 100px;
height: 100px;
background: #33d9b2;
}
</style>
<body>
<div class="box1">
box1
<div class="box2">box2</div>
</div>
</body>
➡️ box2
가 부모인 box1
기준으로 이동하는 것을 알 수 있다.