JavaScript

Get the browser scrollbar width and apply it to CSS

I implemented this because I needed to know the width of the scroll bar when creating a site using VW.


const setSB = function () {
    let scrollbarWidth = window.innerWidth - document.body.clientWidth;
    document.documentElement.style.setProperty('--sb', `${scrollbarWidth}px`);
}
window.addEventListener('DOMContentLoaded', setSB);
window.addEventListener('resize', setSB);

Now you can get the width of the scrollbar.


width:calc(100vw - var(--sb));

The width of the entire screen excluding the scroll bar can be set using the above CSS.