html & css/개념

포지션 (position)

Doo Hee 2023. 11. 22. 12:11

포지션(position)

- html 태그가 화면상에 어디에 위치할 것인가를 결정하는 것

- relative, static, sticky, absolute

 

Static

- CSS의 각각의 요소들은 포지션의 기본값을 가지고 있다. (= static)

- static값으로 지정하면 요소는 left, right, bottom, top 등의 offset을 무시하고 원래 위치에 정적으로 위치하게 된다.

- 포지션 타입을 지정하지 않은 상태 혹은 위치와 관련된 설정을 하지 않은 상

 

Relative

- 원래 위치해야하는 곳을 기준으로 상대적으로 100px만큼 왼쪽으로 가게하고싶으면 relative로 지정하면 된다.

- left, right 같은 offset을 지정하기 위해선 최소 relative라고 하는 포지션 타입을 지정해야한다.

- 즉, 포지션 타입이 relative일 때 비로소 offset을 사용할 수 있다.

<!DOCTYPE html>
<html>
  <head>
    <style>
      html {
        border: 1px solid gray;
      }

      div {
        border: 5px solid tomato;
        margin: 10px;
      }

      #me {
        position: relative;
        left: 100px;
        top: 100px;
      }
    </style>
  </head>
  <body>
    <div id="other">other</div>
    <div id="parent">
      parent
      <div id="me">me</div>
    </div>
  </body>
</html>

여기선 id값이 me인 div태그가 부모에 대해서 상대적으로 위치한다.

 

Absolute

- parent의 포지션이 static(값을 지정X)일 경우: html태그의 위치를 기준으로 위치를 지정

- parent의 포지션이 static(값을 지정X)이 아닐 경우: static이 아닌 부모가 나타날 때까지 무시하다가 static이 아닌 부모가 나타나면 그 부모의 위치를 기준으로 해서 offset값을 지정한다.

- offset 값을 지정하면 html 위치를 기준으로 삼지만, offset을 지정하지 않으면 부모의 위치를 기준으로 한다.

-> absolute를 지정하게 되면 absoulute의 left와 top은 0이 아니라 부모 엘리먼트를 기준으로 자기가 원래 위치해야될 위치에 그 위치가 기본값으로 지정되기 때문이다. 기본값은 자기가 원래 있기로 기대되는 곳이다.

- absolute시 부모의 소속이 아니다. 링크가 끊기면서 부모태그와 무관해짐

-> me라는 태그가 마치 parent의 자식이 아닌 것처럼 표현됨

- 마찬가지로 자식태그도 링크가 끊겨서 부모의 크기의 100%만큼 썼다가 자기 자신의 콘텐츠 크기만큼 변한다.

<!DOCTYPE html>
<html>
  <head>
    <style>
      #parent,
      #other,
      #grand {
        border: 5px solid tomato;
      }

      #grand {
        position: relative;
      }
      #me {
        background-color: black;
        color: white;
        position: absolute;
        left: 0;
        top: 0;
      }
    </style>
  </head>
  <body>
    <div id="other">other</div>
    <div id="grand">
      grand
      <div id="parent">
        parent
        <div id="me">me</div>
      </div>
    </div>
  </body>
</html>

부모와 자식 태그의 링크가 끊기지 않은 상태
부모와 자식 태그의 링크가 끊긴 상태

Fixed

- 스크롤과는 무관하게 자신의 위치에 고정되어있다.

- 특정한 엘리먼트를 화면에 그 위치에 고정시켜서 스크롤로부터 완전히 독립하는 것

- width와 height를 지정하지 않으면 absolute와 같이 콘텐츠 만큼의 크기만큼의 부피를 가진다.

- fixed 엘리먼트의 부모 엘리먼트는 자식 엘리먼트와 링크가 끊겼기 때문에 부모 엘리먼트의 크기는 자식 엘리먼트의 크기를 포함하지 않는다.

<!DOCTYPE html>
<html>
  <head>
    <style>
      #parent,
      #other,
      #grand {
        border: 5px solid tomato;
      }

      #large {
        height: 10000px;
        background-color: tomato;
      }
      #me {
        background-color: black;
        color: white;
        position: fixed;
        left: 0;
        top: 0;
      }
    </style>
  </head>
  <body>
    <div id="other">other</div>
    <div id="parent">
      parent
      <div id="me">me</div>
    </div>
    <div id="large">large</div>
  </body>
</html>