Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does offsetWidth show incorrect value?

I wrote this code.

When I added scroll-bar, I got 403 as clientWidth, and this seems like true: 403px for inner content + 17px for scroll-bar. And then I got 403 as offsetWidth, but offsetWidth must include scroll-bar width. Therefore I should get 403+17, not 403.

Why do I get 403 as result in (*)?

let html = document.documentElement
console.log(window.innerWidth) // 420 on my test
console.log(html.clientWidth) // 420
console.log(html.offsetWidth) // 420

html.style.overflowY = 'scroll' // add scroll-bar
console.log('Window: ' + window.innerWidth) // Window: 420
console.log('clientWidth: ' + html.clientWidth) // clientWidth: 403
console.log('offsetWidth: ' + html.offsetWidth) // offsetWidth: 403 (*)
like image 721
dedavarera Avatar asked Aug 29 '26 07:08

dedavarera


1 Answers

You almost got us! But there it is...

Take a closer look at the documentElement.

Layout of documentElement

The scrollbar is not included! Therefore the only way to get the site width including scrollbars is window.innerWidth.

The read-only Window property innerWidth returns the interior width of the window in pixels. This includes the width of the vertical scroll bar, if one is present.

The value of offsetWidth will include scrollbars for all elements except the documentElement.
offsetWidth of documentElement includes scrollbars, but it simply doesn't have any. Which means that offsetWidth and clientWidth are the same.

like image 171
František Vojáček Avatar answered Aug 30 '26 19:08

František Vojáček



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!