Get scrollbar width in JavaScript

Another one-liner 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:

  • Windows: IE9, IE10, IE11, Edge
  • MacOS: Safari, Firefox, Chrome, Opera
  • iOS: Safari, Chrome
  • Android: Chrome

Comments (5)

Jandro Rojas
06. Jul 2018, 11:37

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, 13:08

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!

Patrick
29. Jan 2020, 06:41

Really elegant solution (which actually works!). Why (on earth) are there so many solutions which create a div

Damien
19. Feb 2020, 18:37

I have been searching for a solution to my site for days! Thank you so much!

Jarón
27. Nov 2020, 10:43

Thanks a lot! I've now implemented it like this:

function getScrollbarWidth(elm) {
  if (elm === document.body) {
    return window.innerWidth - document.documentElement.clientWidth;
  } else {
    return elm.offsetWidth - elm.clientWidth;
  }
}