[카카오톡 클론코딩] # 3.13 Relative, Absolute

Gata·2023년 8월 8일
0

1. Position: static (디폴트 값)

  • 레이아웃이 박스를 처음 위치하는 곳에 두는 것
<!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>

2. Position: relative

  • div를 아주 조금 이동시키고 싶을 때
  • top, bottom, left, right 속성을 사용할 수 있다.
  • element가 처음 놓인 자리를 기준으로 상하좌우로 움직인다.

예시

  • green div에 relative를 적용해보았다.

  • green div를 위로(top) -10px, 왼쪽으로(left) -10px 조금 옮겼다.
    속성값을 이렇게 쓰면 green div가 이렇게 움직이는구나!

3. ⭐Position: absolute

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)

부모 div가 relative할 때

  • 부모 div (wheat색 div)가 relative하고 자식 div (green색 div)가 absolute하면 green div는 body가 아닌 wheat div를 기준으로 움직인다.

업로드중..

정리

green div(자식)를 absolute로 하면 green div를 내가 원하는 좌표대로 움직일 수 있다. body 기준으로 움직이는게 싫으면 green div의 부모인 wheat div를 relative하게 만든다. 만얀 relative한 부모를 찾지 못하면 body를 기준으로 움직이게 된다.

profile
개발은 즐거워🪇

0개의 댓글

관련 채용 정보