[HTML/CSS] CSS의 Position속성

    본 포스팅은 우선 CSS의 작성법 이해했다는 가정하에 작성되었습니다. 잘 모르겠으면 관련 포스팅을 참조해주세요.

     

     

    Position은 요소의 위치를  지정할 방식을 지정합니다.

    * Static - 기본값

    * Relative - 원래 위치를 기준

    * Fixed - 웹브라우저창을 기준

    * Absolute - 웹문서를 기준

     

    태그

    속성

    속성값

    비고

    style

    position

     static

     기본값

     relative

     기본값를 기준으로 한 위치

     fixed

     웹브라우저창을 기준으로 한 위치

     absolute

     웹문서를 기준으로 한 위치

    Position은 레이아웃을 구성하는 가장 중요한 속성으로 웹페이지의 형태를 잡기 위해 사용합니다.

     

     

    <!DOCTYPE html>
    <html>
      <head>
        <title>Position</title>
          <style>
            .bg {width: 400px; height: 400px; background: yellow; margin: auto;}
            .static {width: 30px; height: 30px; background: blue; top: 100px; left: 100px; position:static;}
            .relative {width: 30px; height: 30px; background: red; top: 100px; left: 100px; position:relative;}
            .fixed {width: 30px; height: 30px; background: purple; top: 100px; left: 100px; position:fixed;}
            .absolute {width: 30px; height: 30px; background: green; top: 110px; left: 110px; position:absolute;}
          </style>
      </head>
      <body>

        <div class="bg">
          <div class="static"></div>
          <div class="relative"></div>
          <div class="fixed"></div>
          <div class="absolute"></div>
        </div>

      </body>
    </html>

    노란색 : 배경 요소

    파란색(static) : 기본값으로 문서 흐름에 맞게 위치, 값을 주어도 변하지 않음

    빨간색(relative) : 기본값을 기준으로 한 위치, 예제에선 문서 흐름에 따라 파란색 다음에 위치 해야 하므로 그곳을 기준으로 이동하며 자신의 태그를 감싸고 있는 부모태그가 있다면 부모태그를 기준으로함

    보라색(fixed) : 문서 흐름과 상관없이 웹브라우저창을 기준으로 한 위치, 모니터에 포스트잇을 고정한 것처럼 스크롤을 움직여도 고정되어있으며 포토샵의 레이어처럼 다른요소와 겹쳐짐

    녹색(absolute) : 문서 흐름과 상관없이 웹문서 자체를 기준으로 한 위치, 절대값으로 포토샵의 레이어처럼 다른요소와 겹쳐짐

     

     

    Z-Index : fixed나 absolute의 경우 요소가 겹치기 때문에 작성한 순서가 매우 중요하며 나중에 작성한 요소가 가장 위에 표시됩니다. 위 예제에서는 absolute를 나중에 작성했기 때문에 fixed보다 위에 위치했습니다. 하지만 일일히 순서를 따져가며 작성하기엔 어려움이 따르므로 Z-Index속성으로 순서를 지정합니다. 쉽게 말해 레이어의 순서를 정한다고 생각하면 됩니다. 숫자가 높을수록 위에 위치합니다.

    예)

    .fixed {width: 30px; height: 30px; background: purple; top: 100px; left: 100px; position:fixed; z-index: 10;}
    .absolute {width: 30px; height: 30px; background: green; top: 110px; left: 110px; position:absolute; z-index; 5;}

     

     

    < 연습하기 >

     

    w3스쿨js피들

     

     

     

     

     

    Posted by 옹봉이