Jump to content

Get scrollbar width in JavaScript

Posted in JavaScript · 1 minute read

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)

27. November 2020
Jarón

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;
  }
}
19. February 2020
Damien

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

29. January 2020
Patrick

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

6. July 2018
Stanko

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!

6. July 2018
Jandro Rojas

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.