15 Dec 2017

This article will take less than 1 minute to read.
2 Comments

Another onliner I love, that returns body scrollbar width. If scrollbar is not shown it will return zero (including mobile devices).

function getScrollbarWidth() {
  return window.innerWidth - document.documentElement.clientWidth;
}

Click on the button to try it yourself:

Browser support

Tested on:

Category
JavaScript

Comments (2)

Jandro Rojas
06 Jul 2018, 11:37 AM

What about something more generic? what about a regular div for example? A more general approach would be:

function getScrollbarWidth(element) {

return element.scrollWidth - element.clientWidth;

}

The scrollWidth property will include the with of the vertical scrollBars even if there is no horizontal scrolling...this works in all major browsers.

Stanko
06 Jul 2018, 01:08 PM

Hello Jandro,

Actually that is not going to work. To get element's scrollbar width you need to use .offsetWidth instead of .scrollWidth.

Check MDN documentation on it:

"The width is measured in the same way as clientWidth: it includes the element's padding, but not its border, margin or vertical scrollbar (if present)."

So the correct way would be:

function getScrollbarWidth(element) {
return element.offsetWidth - element.clientWidth;
}

Please note that this will not work on body therefore you need to use the method from the blog post.

Hope that helps, cheers!

Leave a comment

Sending failed, please try again.
Thank you! Your comment is sent. Please note that all of the comments go through moderation.