How to make a scrollbar with responsive width?

Hello people!
Story Format: SugarCube 2.30

So, I can set the scrollbar width:

#view::-webkit-scrollbar {
    width: 100px;
}

But if you resize the window of course the scrollbar becomes larger in proportion to everything else (which is responsive), which gets in the way of things. But if I set the width to say “10%” the scrollbar vanishes completely. How do get it to stop doing that? And if that isn’t possible, what workaround can I use to somehow build a responsive scrollbar another way?

One option I thought of was to make a scrollbar with javascript, but I don’t know javascript. These people did it:
One
Two
but I don’t know how to use their examples to simply make the scrollbar width responsive, and have the other things customizable in the usual css way. Maybe I could get there with a lot of experimentation…

Thank you!

How about using the CSS method, with a percentage to make it responsive, but adding a min-width property in pixels to make sure it never get smaller than that? Does that work?

There’s also this:

https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-width

If min-width is in pixels the scrollbar just goes to min-width and isn’t responsive; if I set min-width as a percentage then the scrollbar vanishes completely still. :man_shrugging:

“scrollbar-width” is only supported by Firefox, and apparently is only for switching between predetermined styles, not actually setting a custom width.

Ah. Well, ::-webkit-scrollbar is only supported by WebKit browsers (ie. not Firefox), so there are no universal CSS solutions here, unfortunately. The best bet might be JavaScript.

Edit: It seems like percentages should work, according to WebKit themselves… Not sure why it doesn’t. That blog post is from 2009 though.

1 Like

“percentage of the viewport area” it says; maybe some of the other settings are interfering with its interaction with the viewport height? I’ll see… Nope, still not showing up after removing all 100vh and 100vw things.

Here’s some more basic javascript than the first two examples I found; now I’m trying to figure out how to use it to make a horizontal overlay scrollbar with 18% height.

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>HTML DOM</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link href="/demo/styles.css" rel="stylesheet">
    <style>
    .grabbing {
        cursor: grabbing;
        user-select: none;
    }
    .thumb {
        cursor: grab;
    }
    </style>
</head>
<body class="font-sans flex justify-center">
    <div id="wrapper" class="border border-gray-400 m-8 max-w-2xl overflow-hidden" style="height: 32rem;">
        <div id="content" class="h-full overflow-auto p-2 pr-4 -mr-4">
            <p class="mb-4">
                Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.
                Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.
                Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.
                Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.
                Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue.
                Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum.
                Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante.
                Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna.
            </p>
            <p class="mb-4">
                Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus.
                Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et arcu.
                Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris. Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc. Nunc nonummy metus. Vestibulum volutpat pretium libero. Cras id dui. Aenean ut
                Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.
                Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.
                Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.
                Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.
            </p>
            <p>
                Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue.
                Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum.
                Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante
                Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna.
                Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus.
                Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et arcu.
                Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris. Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc. Nunc nonummy metus. Vestibulum volutpat pretium libero. Cras id dui. Aenean ut
            </p>
        </div>
    </div>
    <div id="anchor" class="absolute top-0 left-0"></div>
    <div id="scrollbar" class="absolute bg-gray-200 border border-gray-400 border-l-0 w-3">
        <div id="track" class="absolute h-full left-0 top-0 w-full"></div>
        <div id="thumb" class="bg-gray-600 absolute left-0 rounded-full w-full thumb"></div>
    </div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Query elements
    const wrapper = document.getElementById('wrapper');
    const content = document.getElementById('content');
    const anchor = document.getElementById('anchor');
    const scrollbar = document.getElementById('scrollbar');
    const track = document.getElementById('track');
    const thumb = document.getElementById('thumb');

    // Get the bounding rectangles
    const wrapperRect = wrapper.getBoundingClientRect();
    const anchorRect = anchor.getBoundingClientRect();

    // Set the scrollbar position
    const top = wrapperRect.top - anchorRect.top;
    const left = wrapperRect.width + wrapperRect.left - anchorRect.left;
    scrollbar.style.top = `${top}px`;
    scrollbar.style.left = `${left}px`;

    // The scrollbar has the same height as the wrapper
    scrollbar.style.height = `${wrapperRect.height}px`;

    // Set the initial height for thumb
    const scrollRatio = content.clientHeight / content.scrollHeight;
    thumb.style.height = `${scrollRatio * 100}%`;

    let pos = { top: 0, y: 0 };

    const mouseDownThumbHandler = function(e) {
        pos = {
            // The current scroll 
            top: content.scrollTop,
            // Get the current mouse position
            y: e.clientY,
        };

        thumb.classList.add('grabbing');
        document.body.classList.add('grabbing');

        document.addEventListener('mousemove', mouseMoveHandler);
        document.addEventListener('mouseup', mouseUpHandler);
    };

    const mouseMoveHandler = function(e) {
        // How far the mouse has been moved
        const dy = e.clientY - pos.y;

        // Scroll the content
        content.scrollTop = pos.top + dy / scrollRatio;
    };

    const mouseUpHandler = function(e) {
        thumb.classList.remove('grabbing');
        document.body.classList.remove('grabbing');

        document.removeEventListener('mousemove', mouseMoveHandler);
        document.removeEventListener('mouseup', mouseUpHandler);
    };

    const scrollContentHandler = function() {
        window.requestAnimationFrame(function() {
            thumb.style.top = `${content.scrollTop * 100 / content.scrollHeight}%`;
        });
    };

    const trackClickHandler = function(e) {
        const bound = track.getBoundingClientRect();
        const percentage = (e.clientY - bound.top) / bound.height;
        content.scrollTop = percentage * (content.scrollHeight - content.clientHeight);
    };

    content.addEventListener('scroll', scrollContentHandler);
    thumb.addEventListener('mousedown', mouseDownThumbHandler);
    track.addEventListener('click', trackClickHandler);
});
</script>
</body>
</html>

Should I mark this question as solved, and open a new question for changing a vertical javascript scrollbar into a horizontal one?