A Work in Progress

developer's blog by Wei
lots of work in progress notes

Various Content Sizing

November 19, 2020
  • window.innerWidth – viewport width, including scrollbar width, CSS media query uses this
  • document.documentElement.clientWidth – also viewport width
  • element.clientWidth – element width, can use this to get width without scrollbar by document.body.clientWidth
  • element.scrollWidth

Which metric to use to get viewport size

The major differences between the above four widths are mainly about whether they're associated width the window or an element. And more practically, whether they include scrollbar width. The first two include scrollbar width, the last two don't.

Regarding document.documentElement.clientWidth, from _A Tale of Two Viewports**:

If you know your DOM, you know that document.documentElement is in fact the element: the root element of any HTML document. However, the viewport is one level higher, so to speak; it’s the element that contains the <html> element. That might matter if you give the <html> element a width. (I don’t recommend that, by the way, but it’s possible.)

In that situation document.documentElement.clientWidth and -Height still gives the dimensions of the viewport, and not of the <html> element. (This is a special rule that goes only for this element only for this property pair. In all other cases the actual width of the element is used.)

For consistency, we should use metric that is used by CSS media queries.

Recent testing with media queries shows that window.innerWidth is used for CSS media queries, which coincides with document.documentElement.clientWidth as well.

Other trivias

In Chrome, when you open dev tools, it displays a viewport size (with my current version Version 86.0.4240.198 (Official Build) (x86_64) this shows up on the top right corner). This viewport size assumes that you're using 100% zoom ratio. If you zoom in or zoom out, the actual viewport resizes, but this resported dimensions won't change.

This is the most helpful article thus far: