[CSS] position relative와 absolute

Carrie·2023년 12월 30일
0
post-thumbnail

position: relativeposition: absolute의 차이와 관계성에 대해 알아보자

우선 2개의 박스를 준비한다.

🧭 position: relative

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

position: absoluterelative 속성을 가진 부모의 위치 기준으로 움직인다.

<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를 기준으로 이동한다.

🧭 position: relative와 position: absolute

absoluterelative기준으로 이동시키려면 relative 속성이 적용된 부모 아래에 있어야 한다. 즉, box2box1에 넣어주어야 한다. 하지만 아래와 같이 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>

➡️ absoluterelative 기준으로 움직이지 않는다. 두 박스에 동일한 속성 absolute를 주었을 때와 똑같이 이동한다. box2box1이 아닌 body 기준으로 움직이기 때문이다.

🧭 position: relative와 position: absolute의 관계

absoluterelative기준으로 이동시키기 위해 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 기준으로 이동하는 것을 알 수 있다.

📌 참고

http://www.kiss7.kr/db/board.php?bo_table=siteblog&wr_id=22

profile
Markup Developer🧑‍💻

0개의 댓글