레이아웃 (4) - 배치 관련 스타일(position) (23.06.09)

·2023년 6월 9일
0

CSS

목록 보기
6/15
post-thumbnail

📝 배치 관련 스타일(position)

position은 요소의 위치를 지정하는 속성


💡 position : relative; (상대적인)

  • 지정된 요소 내부에 다른 요소가 상대적인 위치를 지정할 수 있도록 기준이 되게 만드는 속성

  • 내부에 작성되는 요소에 위치 지정 시 top, bottom, left, right 속성을 사용할 수 있음

💡 position : absolute; (절대적인)

  • 기본 요소의 배치 순서를 무시하고 지정된 절대 위치에 요소를 배치함

💡 position : fixed; (고정된)

  • 항상 고정된 위치에 요소를 배치함 (화면이 움직이든 말든 항상 같은 위치)

✏️ 예시

  • html
    <div class="container-1">
        <div class="first"></div>
        <div class="second"></div>
        <div class="third"></div>
    </div>

    <!-- absolute의 특징 중 절대적인 위치에 배치되는 특징은
         body 태그의 자식인 경우에만 가능하다.
    -->
    <div class="third"></div>
  • css
div{
    border: 1px solid black;
    box-sizing: border-box;
    /* -> width/height 값이
    content + padding + border 합한 값에 맞게
    알아서 비율 조정
    */
}

.container-1{
    border: 2px dashed red;

    position: relative;
    /* 내부에 작성되는 요소에
    상대적인 위치(top/bottom/left/right)를 지정할 수 있음
    */
}

.first{
    width: 300px;
    height: 300px;
    background-color: yellow;
}

.second{
    width: 200px;
    height: 200px;
    background-color: green;

    position: absolute; /* 요소 기존 배치 무시(겹치기) 가능 */
    /* + 상위 요소가 relative -> 내부에 아무 위치 배치 가능 */

    top : 50px; /* 위쪽에서 얼마큼 떨어지겠다 */
    left : 50px; /* 왼쪽에서 얼마큼 떨어지겠다 */
}

.third{
    width: 100px;
    height: 100px;
    background-color: red;

    position : absolute;

    top: 100px;
    left: 100px;
}



📌 요소를 영역 정 가운데에 배치하기

✏️ 예시

  • html
    <h2>요소를 영역 정 가운데에 배치하기</h2>
    <div class="container-2">
        <div id="center"></div>
    </div>

    <div class="fixed-area">
        <a href="#body-top">위쪽으로 이동</a>
        <!-- #은 임시 값 -->
    </div>
  • css

/* 정 가운데에 배치하기 */

.container-2{
    width: 300px;
    height: 300px;
    position: relative; /* 내부 요소 상대 위치 지정 */
}

#center{
    width: 50px;
    height: 50px;
    background-color: pink;

    /* relative 내부 요소 중
       position이 absolute(4방향) top/bottom 등을 사용할 수 있다.
    */
    position: absolute;

    /* 사방으로 요소를 당김 */
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    margin: auto;
}

/* fixed */

.fixed-area{
    width: 120px;

    /* align : 맞추다, 정렬하다 */
    text-align: center;

    position: fixed;
    /* fixed 요소는 화면(뷰포트, 브라우저) 기준으로 배치됨
        + 다른 요소와 겹쳐질 수 있고,
          별도로 화면을 차지하려고 하지 않음
    */

    bottom: 50px;
    right: 50px;
}


profile
풀스택 개발자 기록집 📁

0개의 댓글