<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
height: 1000vh;
margin: 50px;
}
div{
width: 300px;
height: 300px;
background-color: wheat;
position: static;
}
</style>
</head>
<body>
<div>
</div>
</body>
</html>
처음 놓인 자리를 기준
으로 상하좌우로 움직인다.green div에 relative를 적용해보았다.
green div를 위로(top) -10px, 왼쪽으로(left) -10px 조금 옮겼다.
속성값을 이렇게 쓰면 green div가 이렇게 움직이는구나!
absolute는 relative한 부모가 늘 필요하다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
height: 1000vh;
margin: 50px;
}
div{
width: 300px;
height: 300px;
background-color: wheat;
}
.green{
background-color: teal;
height: 100px;
width: 100px;
bottom: 0px;
right: 0px;
position: absolute;
}
</style>
</head>
<body>
<div>
<div class="green"></div>
</div>
</body>
</html>
absolute는 늘 relative한 부모가 필요하다.
<body>
- 가장 바깥쪽에 있는 늘 relative한 부모
<div></div>
- relative하지 않은 부모 div
<div class="green"></div>
- absolute한 자식 div
absolute는 가장 가까운 relative 부모를 기준으로 이동한다. 위 코드의 경우 green div의 부모인 wheat div가 relative하지 않기 때문에 body를 가장 가까운 relative한 부모로 삼고 이를 기준으로 상하좌우로 이동한다.
아래 이미지의 경우 (body기준으로 bottom: 0px, right: 0px)
green div(자식)를 absolute로 하면 green div를 내가 원하는 좌표대로 움직일 수 있다. body 기준으로 움직이는게 싫으면 green div의 부모인 wheat div를 relative하게 만든다. 만얀 relative한 부모를 찾지 못하면 body를 기준으로 움직이게 된다.