Get the Width of Scrollbar Using JavaScript

JavaScriptPosted on

1 min read

It can be handy to know the width of the scrollbar. A frequent example can be a modal. In a case of a modal, we usually want to disable the outside scroll on the body element. For this, we add overflow: hidden; to the body, the scrollbar will disappear, and our content will shift into its place.

Get the Width of the Browser Scrollbar

This shift is annoying, and one way to avoid it to add an offset (when the overflow hidden is present) to the right side of theelement. For this, we must get the current width of the scrollbar. If you want to get the browser’s scrollbar width, you can use the following:

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

With the window.innerWidth, we will get the width of the browser. Width the document.documentElement.clientWidth we will get the width of our document (without the scrollbar). If we subtract them from each other, we will get the scrollbar width.

Get the Width of the Scrollbar on Any Element

We can also measure the scrollbar width on any element with a slightly modification. Insted of using the window object we need to get the element.offsetWidth:

function getElementScrollbarWidth(element) {
    return element.offsetWidth - element.clientWidth;


Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in JavaScript category