[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/scrollbar-width [Back]  [Original]

What is the scrollbar width?
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    back to the lesson

    What is the scrollbar width?

    importance: 3

    Write the code that returns the width of a standard scrollbar.

    For Windows it usually varies between 12px and 20px. If the browser doesnt reserve any space for it (the scrollbar is half-translucent over the text, also happens), then it may be 0px.

    P.S. The code should work for any HTML document, do not depend on its content.

    solution

    To get the scrollbar width, we can create an element with the scroll, but without borders and paddings.

    Then the difference between its full width offsetWidth and the inner content area width clientWidth will be exactly the scrollbar:

    // create a div with the scroll
    let div = document.createElement('div');
    
    div.style.overflowY = 'scroll';
    div.style.width = '50px';
    div.style.height = '50px';
    
    // must put it in the document, otherwise sizes will be 0
    document.body.append(div);
    let scrollWidth = div.offsetWidth - div.clientWidth;
    
    div.remove();
    
    alert(scrollWidth);

    Web Proxy Viewer  |  New URL  |  Original Page