Element Sizes & Scrolling

Sample element

<div id="example">...Text...</div>
<style>
  #example {
    width: 300px;
    height: 200px;
    border: 25px solid #e6e6e6;
    padding: 20px;
    overflow: auto;
  }
</style>
Sample element

Mind the scrollbar. If the scrollbar is 16px wide then the content width remains only 300 - 16 = 284px.

Geometry

Here's the overall picture with geometry properties:

Geometry picture

Don't take width/height from CSS

We should use geometry properties instead of getComputedStyle:

  1. CSS width/height depend on another property: box-sizing that defines what is CSS width and

  2. CSS width/height maybe auto

  3. A scrollbar

Window sizes and scrolling

Width/height of the window

documentElement.clientHeight;
documentElement.clientWidth;

Not window.innerWidth/innerHeight

alert(window.innerWidth); // full window width
alert(document.documentElement.clientWidth); // window width minus the scrollbar

Width/height of the document

Theoretically, as the root document element is document.documentElement, and it encloses all the content, we could measure the document's full size as document.documentElement.scrollWidth/scrollHeight.

But on that element, for the whole page, these properties do not work as intended. In Chrome/Safari/Opera, if there's no scroll, then documentElement.scrollHeight may be even less than documentElement.clientHeight ! Weird, right?

To reliably obtain the full document height. we should take the maximum of these properties:

let scrollHeight = Math.max(
  document.body.scrollHeight,
  document.documentElement.scrollHeight,
  document.body.offsetHeight,
  document.documentElement.offsetHeight,
  document.body.clientHeight,
  document.documentElement.clientHeight
);

Get the current scroll

DOM elements have their current scroll state in their scrollLeft/scrollTop properties.

For document scroll: document.documentElement.scrollLeft/scrollTop

Speical properties: window.pageXOffset/pageYOffset

For historical reasons, these properties are the same:

  • window.pageXOffset is an alias of window.scrollX

  • window.pageYOffset is an alias of window.scrollY

Scrolling: scrollTo, scrollBy, scrollIntoView

scrollIntoView

The call to elem.scrollIntoView(top) scrolls the page to make elem visible. It has one argument:

Forbid the scrolling

document.body.style.overflow = "hidden";