요소 사이즈와 스크롤

lee jae hwan·2022년 8월 12일

브라우저

목록 보기
19/39

요소노드는 스타일에 설정된 크기로 화면에 자리를 차지하는데 기본적으로 html코드 위치에따라 다른 컨텐츠와 자리를 잡는다.

브라우저는 요소노드의 너비나 높이 같은 기하관련 프로퍼티를 제공하며 자바스크립트로 요소를 움직이거나 특정 좌표에 위치시킬 수 있다.

<div id="example">
  ...텍스트...
</div>
<style>
  #example {
    width: 300px;
    height: 200px;
    border: 25px solid #E8C48F;
    padding: 20px;
    overflow: auto;
  }
</style>

화면에서 요소노드가 차지하는 크기는 패딩, 테두리등 스타일에 영향을 받는다.

width: 300px; height: 200px; 순수 컨텐츠의 넓이와 높이를 설정
만약 스크롤바가 있다면 16px의 크기가 줄어든다.
(스크롤바의 크기와 컨텐츠크기를 합한값이 프로퍼티 값이 된다.)

padding: 20px; 컨텐츠크기 외부에 빈영역을 설정한다.

border: 25px solid #E8C48F; 패딩 외부 테두리두께를 설정한다.


브라우저는 요소노드의 스타일속성을 계산하여 기하프로퍼티값을 제공한다.




기하프로퍼티

브라우저가 제공하는 기하프로퍼티 대부분은 읽기전용이지만 scrollLeft와 scrollTop은 변경이 가능하다.


offsetParent, offsetLeft, offsetTop

offsetParent프로퍼티는 해당 요소를 렌더링할 때, 좌표계산에 사용되는 가장 가까운 조상요소(the closest positioned ancestor element)의 참조를 반환한다.

상위요소노드를 기준으로 요소노드의 위치를 설정하기 때문에 상위요소노드가 어떤 노드인지가 중요하다.

  1. CSS position프로퍼티가 absolute, relative, fixed, sticky인 가장 가까운 조상 요소
  2. < td >나 < th >, 혹은 < table >
  3. < body >
    상위요소는 위3가지중 1가지가 될 수 있다.
<main style="position: relative" id="main">
  <article>
    <div id="example" style="position: absolute; left: 180px; top: 180px">...</div>
  </article>
</main>
<script>
  alert(example.offsetParent.id); // main
  alert(example.offsetLeft); // 180 (주의: 문자열 '180px'이 아닌 숫자 180이 반환됩니다.)
  alert(example.offsetTop); // 180
</script>

< div id="example" style="position: absolute; left: 180px; top: 180px" >...< /div >
div는 상위요소로부터 좌 180px, 상 180px거리에 위치시키라는 스타일속성이다. 그러나 div style.position속성이 absolute, relative, fixed, sticky인 경우에만 위치속성이 유효하다.

main이 example의 상위요소노드가 되고 example은 position: absolute;로 설정되어 left: 180px; top: 180px; 위치에 자리잡게 한다.



getComputedStyle(elem)로 요소노의 스타일속성값을 알 수 있지만

브라우저는 요소노드의 기하프로퍼티로 offsetParent, offsetLeft, offsetTop, offsetWidth와 offsetHeight, clientTop, clientLeft,clientWidth, clientHeight, scrollWidth, scrollHeight, scrollLeft, scrollTop프로퍼티를 기본으로 제공하기 때문에 getComputedStyle를 사용하지 않아도 된다.



let st = getComputedStyle(example);
console.log('width : '+st.width): // 300
console.log('padding : '+st.padding): // 20
console.log('border : '+st.border): // 25

console.log( 'clientWidth : '+ example.clientWidth ); // 340
console.log( 'offsetWidth : '+ example.offsetWidth ); // 390

clientWidth는 st.width에 양쪽 패딩 20씩더한 값이 된다.
offsetWidth는 clientWidth에 양쪽 테두리 25씩 더한 값이 된다.


scrollHeight 프로퍼티는 스크롤바에 의해 감춰진 영역도 포함한다는 점에서 차이가 있다.

scrollTop은 세로스크롤이 아래로 움직임에 따라 가려진 영역의 너비와 높이를 나타낸다.



CSS로 스타일이 지정된 요소노드는 브라우저가 기하프로퍼티를 설정해주므로 기하프로퍼티로 구할 수 있는 것을 getComputedStyle메소드로 구할 필요가 없으며 여러가지 이유로 부정확할 수 있다.

0개의 댓글