⭐️ position에 대하여

팔리동·2021년 8월 3일
0

css

목록 보기
2/4

position에 대해서 알아보자

🎨 position

  • css의 position 속성은 HTML에서 element를 배치하는 방법을 지정하는 속성이다.
  • position속성에 쓸 수 있는 값은 5개가 있다.
  1. static
  2. relative
  3. absolute
  4. fixed
  5. stick

static(기본값)

  • element에 position을 지정하지 않았을 때 기본으로 적용되는 값이 static이다.

  • static의 경우 top, right, bottom, left, z-index속성들의 효과가 안먹는다.

relative

  • relative값을 지정하면 static에서 못쓰던 top, right, bottom, left, z-index를 쓸 수 있다.

  • relative를 지정한 요소는 원래 요소가 위치한 곳을 기준으로 움직인다.

<style>
        div {
            position:relative;
            top: 100px;
        }
    </style>
<div>hello</hello>

  • relative가 적용된 요소는 다른 요소에게 영향을 미치지 않는다.

  • 가장 중요한 것은 원래 위치한곳을 기준으로 움직인다는 것

absolute

  • absolute는 relative와 다르게 원래 위치한 곳을 기준으로 따르지 않고 부모태그를 기준으로 움직인다.

  • 부모 중에 position이 relative, fixed, absolute 하나라도 있으면 그 부모에 대해 절대적으로 움직이게 됩니다.

예제 코드를 보자

<style>
        .hello1 {
            width: 300px;
            height: 300px;
            background-color: aqua;
            margin-top: 30px;
            
        }
        .hello2 {
            margin-top: 30px;
            width: 100px;
            height: 100px;
            background-color: blueviolet;
        }
    </style>
<body>
  <div class="hello1">
    <div class="hello2"></div>
  </div>
</body>  


보라색 div상자는 밝은 옥색 상자안에 있다.
이제 보라색 상자에 absolute속성을 부여해보자

<style>
        .hello1 {
            width: 300px;
            height: 300px;
            background-color: aqua;
            margin-top: 30px;
            
        }
        .hello2 {
            position: absolute;
            top: 30px;     >>>>>>>>>>> 추가
            margin-top: 30px; >>>>>>>> 추가
            width: 100px;
            height: 100px;
            background-color: blueviolet;
        }
    </style>
<body>
  <div class="hello1">
    <div class="hello2"></div>
  </div>
</body>  

  • 보라색 상자가 밝은 옥색 상자를 기준으로 30px내려갔다.
    만약 absolute를 지정한 태그의 부모가 없으면 body태그를 기준으로 움직인다.

  • absolute값은 부모태그를 기준으로 움직인다.

fixed

  • fixed는 스크린의 뷰포트(viewport)를 기준으로 한 위치에 배치된다.
    쉽게 말해서 스크롤을 해도 고정되어있는 nav bar같은 것을 구현할 때 쓰인다.

    사진으로 표현은 안되만 위 아래 좌우로 스크롤을 옮겨도 보라섹 박스의 위치는 고정된다.

sticky

  • sticky는 fixed의 고통점은 둘다 스크롤을 움직여도 똑같이 보인다. 차이점은 fixed는 문서의 흐름을 따르지 않고 뷰포트를 기준으로 배치 되는 반면 sticky는 문서의 흐름을 따르면서 부모태그를 기준으로 상대적인 위치에 배치된다.
<style>
        body {
            height: 3000px;
            width: 3000px;
        } 
        .hello1{
            
            width: 100px;
            height: 100px;
            background-color: blueviolet;
        }
        .hello2{
            position: sticky;  >>>> 주목
            top: 30px;
            width: 100px;
            height: 100px;
            background-color:aqua;
        }
    </style>
<body>
        <div class="hello1">
            형님!
        </div>
        <div class="hello2">
            아우!
        </div>
    
</body>

스크롤을 내려보면!

fixed를 쓰면 다른 요소랑 겹칠 우려가 있는데 sticky는 그러한 문제를 방지할 수 있다.

profile
배움의 기록

0개의 댓글