[CSS] position

나는경서·2021년 11월 5일
3
post-thumbnail

position의 종류에는 ...

  • static
  • relative
  • absolute

static

따로 position 속성값을 주지 않았다면 static 값을 가집니다. 즉, html 마크업 한 순서대로 위치가 지정되게 됩니다.이 속성값은 부모 객체에서 다른 position 속성값이 주어졌을 때 무시하기 위해 사용될 때가 있습니다.

relative

relative 는 자신이 원래 있어야 할 위치, 즉 static에 상대적입니다. position: relative;을 주고 이 기준점으로 top,left,right,bottom 을 주면 이동하게 됩니다.(top과 bottom을 동시에 같은 값을 주면 top이 선택되고 right와 left를 동시에 같은 값을 주면 left쪽으로 이동합니다.)

.box2{
    position:relative;
    background-color: red;
    color:white;
    width: 100px;
    height: 100px;
    top: 20px;
    left: 20px;
  }

absolute

absolute는 절대적입니다. position: absolute;라고 한 뒤 top : 30px; left: 50px;이라고 추가적 값을 주면 동떨어진 박스가 하나 놓여있습니다. 이들은 기준점이 html 위치에 있기에, 왼쪽 제일 상단이 본래 자신의 위치라고 생각하고 움직이게 됩니다.

box3position: absolute;를 주고 아무 값도 주지 않으면 static(자기 본위치)에 놓이게 됩니다.

하지만 값을 주면 맨 왼쪽 상단을 기준으로 놓이게 됩니다. top:0; left:0;을 준 그림입니다.

부모요소와 자식요소 간 relative 와 absolute

⭐️ 그러나, 이 absolute도 바로 부모 요소에 의해 움직입니다. relative, absolute, fixed 같은 position 속성이 부모에 놓여있다면, absoluteposition 속성을 가진 가장 가까운 부모의 박스 내를 기준으로 위치하게 됩니다.

밑 코드를 보면 box2에게 position:absolute;를 줬기 때문에 box2는 부모 요소인 box1을 기준으로 움직입니다. 그러므로 box2box1에서 40px 내려왔습니다.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>relative-absolute</title>
  <link rel="stylesheet" href="reset.css">
  <style>
  .box1{
    position:relative;
    top:40px;
    background-color: green;
    color:white;
    width: 100px;
    height: 100px;
  }
  .box2{
    position:absolute;
    top: 40px;
    background-color: red;
    color:white;
    width: 100px;
    height: 100px;
  }
  </style>
</head>
<body>
  <div class="box1">box1
    <div class="box2">
      box2
    </div>

  </div>
</body>
</html>

여기서 box2absolute가 아닌 position:relative;를 주면 box1 기준이 아닌 box2static 을 기준으로 40px 내려온 걸 볼 수 있습니다.

profile
얼레벌레 돌아가는 Frontend Developer

0개의 댓글