1

I made a custom scrollbar and the only problem is that whenever I zoom in or zoom out (Ctrl + mousewheel), the width (width: 10px) changes as it is in pixels. If I change it to width: 1vw, then it works fine with zoom but on window resize it changes again.

Making width: 1vh, also changes the size of scrollbar when resizing window vertically.

So, how to make this scrollbar's size be fixed and independent of zoom/window resizing?

CSS Code

#scroll-bar {
    position: fixed;
    width: 1vh;
    height: 100%;
    top: 0;
    right: 0;
    background: black;
    
}

Javascript Code

<script>
    let bar = document.getElementById('scroll-bar');
    let totalHeight = document.body.scrollHeight - window.innerHeight;
    window.onscroll = function () {
        let bar_height = (window.pageYOffset/totalHeight)*100;
        bar.style.height = bar_height+'%';
    }
</script>

1 Answers1

0

I think you are running into multiple problems there, because vw is always relative to the window width while px will be relative to the zoom.

vh is always relative to the window height, so this probably is totally wrong for your usecase.

You can however add min-width and max-width to your scrollbar to set upper and lower boundaries.

#scroll-bar {
    position: fixed;
    width: 1vw;
    height: 100%;
    top: 0;
    right: 0;
    background: black;
    min-width:12px;
    max-width:48px;
}

In general I'd rethink your approach to use browser zoom and maybe implement something with javascript instead where you zoom into your content that way, this will leave the scrollbar uneffected.

Another approach could be to fetch/listen for the zoom level of the browser and do calculations for the needed pixel width of your scrollbar: How to detect page zoom level in all modern browsers?

rx2347
  • 1,071
  • 1
  • 6
  • 26