Web 기초

[css] Layout 잡기 1 (position 속성 - relative, absolute, fixed)

Chaedie 2022. 7. 19. 19:29
728x90

오늘은 CSS에서 가장 중요한 "레이아웃"을 잡기 위해 사용되는 position 속성에 대해 포스팅한다.

position : fixed;

{ position : fixed; } 는 상단 바 (nav bar)나 aside bar를 만들기 위해 보통 사용하는 CSS속성이다. 이름에서 유추할 수 있듯, 위치를 고정시키기 때문에 스크롤을 아래로 내려도 상단에 nav bar가 유지되는 걸 구현할 수 있다. 빠르게 코드와 결과물을 보도록 하자.

Relative, Absolute

{ position : relative; } 는 left, right, top, bottom 과 함께 사용하여 위치를 지정할 수 있다. { position : absolute } 는 부모 중에 position이 relative, fixed, absolute 하나라도 있으면 그 부모에 대해 절대적으로 움직인다.

사용 예시

    <style>
      body {
        margin: 0;
      }
       nav {
        display: block;
        width: 100vw;
        height: 10vh;
        background-color: #4267b2;
        color: white;
        text-align: center;
        position: fixed;
        z-index: 1;
      }
      main {
        background-color: aqua;
        position: relative;
        left: 100px;
        top: 100px;
        width: 100px;
        height: 150vh;
      }
      aside {
        background-color: blue;
        color: white;
        position: absolute;
        top: 10px;
        left: 10px;
        width: 200px;
        height: 200px;
      }
    </style>
  ...
  <body>
    <nav>나는 nav bar다</nav>
    <main>
      나는 본문이다~
      <aside>나는 aside다</aside>
    </main>
  </body>

1) nav bar 는 position : fixed;를 사용해 상단에 고정시켰다.
2) main (본문)은 relative를 사용해 위치 시켰고,
3) aside는 main에 대해 절대적으로 위치시켰다.