[CSS] position:absolute인 요소의 width:100%는 무엇의 100%일까?

게코젤리·2023년 2월 16일
1
post-thumbnail

이슈

grid 레이아웃으로 css 스타일링을 하는 중에 position:absolute, width:100%를 부여한 엘리먼트의 width 값이 예상한 것과 다르게 나왔다. 이전까지 width, height의 퍼센트값은 position 속성과 관계없이 부모의 width, height를 참조한다고 생각했기 때문이다.

해결


이것에 대해 구체적으로 설명한 자료는 찾지 못했다. 위는 mozilla의 설명인데 position: absolute 속성을 가진 엘리먼트는 가장 가까운 위치 지정 조상 요소(position 속성이 부여된, static 제외)에 대해 상대적으로 배치한다. 하지만 상대적으로 배치한다는 말이 폭과 높이에도 영향을 준다는 말로 해석되진 않는다.

직접 스타일을 작성하면서 확인해보았다. width, height값도 위의 원리와 마찬가지로 지정되었다.

<style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      .wrap {
        /* position: relative; */
        border: 5px solid blueviolet;
        height: 100vh;
      }

      .row {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        position:absolute;
        top: 200px;
        width: 500px;
        height: 100px;
        border: 5px solid red;
      }

      .box {
        /* position: relative; */
        border: 5px solid teal;
      }

      .option {
        position: absolute;
        width: 100%;
        bottom: 0;
        height: 20px;
        border: 5px solid yellowgreen;
      }
</style>

  <body>
    <div class="wrap">
      <div class="row">
        <div class="box"><div class="option"></div></div>
      </div>
    </div>
  </body>

결론

position: absolute, width: 100%일 때, width:100%는 부모가 아니라 상위 요소 중 position 속성이 부여된(absolute, relative, fixed, sticky) 요소의 width를 상속한다.(height도 마찬가지)

만약 position 속성을 주고 싶은데 부모의 width를 퍼센트로 가져오고 싶다면 relative를 부여하면 된다.

0개의 댓글