Explain Codes LogoExplain Codes Logo

Making the main scrollbar always visible

html
responsive-design
css
browser-compatibility
Anton ShumikhinbyAnton Shumikhin·Aug 31, 2024
TLDR

To keep the vertical scrollbar always visible, employ the CSS property overflow-y: scroll; on either html or body tag.

body { overflow-y: scroll; /* Abra-ka-scrollbar! */ }

This technique guarantees the scrollbar is persistently visible, mitigating layout shifts regardless of content height.

Expanding upon this, we can delve into other facets like enhancing user interaction, ensuring cross-browser compatibility, and customizing scrollbars.

Cross-Browser Scrollbar Visibility

Achieving a consistent scrollbar visibility across different browsers can be a feat, given their various default behaviors and support to scrollbar styling.

Webkit Browsers: Scrollbar Styling

Webkit-based browsers (Safari, Chrome) typically follow an auto-hide mechanism for scrollbars, displaying them only during scrolling. This can lead to varying user experiences depending upon operating system preferences. Use ::-webkit-scrollbar pseudo element to enforce visibility and offer a styling makeover:

/* The spotlight's on you, scrollbar */ ::-webkit-scrollbar { -webkit-appearance: none; width: 10px; } ::webkit-scrollbar-thumb { border-radius: 5px; background-color: darkgray; -webkit-box-shadow: 0 0 1px white; }

Firefox: Scrollbar Compatibility

Older versions of Firefox need specific handling. The -moz-scrollbars-vertical attribute was a popular choice before Firefox 64 to keep a vertical scrollbar intact:

html { overflow-y: scroll; scrollbar-color: black white; /* Updated way to paint scrollbar */ } body { overflow-y: scroll; -moz-scrollbars-vertical: auto; /* For good ol' Firefox */ }

Platform-specific Showdown

Pay heed that MacOS users might experience disappearing scrollbars, courtesy of their system preferences. While using CSS guarantees standardized visuals where system permits, total control over scrollbar visibility requires diving into JavaScript.

Embellishing Scrollbar Styling

Tailoring scrollbars to match your website's aesthetic can be beneficial for visual consistency. Remember to avoid non-standard methods for wider browser compatibility.

Giving Scrollbars a Makeover

/* Scrollbar swaps default garment for a custom-tailored suit */ ::-webkit-scrollbar-thumb { background: #888; /* Stylish color for our thumb model */ border-radius: 10px; /* Abstract runway vibe with rounded edges */ }

Avoiding Styling Missteps

Steering clear from hacks like setting height to 101% to force a scrollbar as it may lead to unwanted cropping or the dreaded double scrollbar scenario. Consider opting for min-height with slight overflow, or padding to ensure presence of scrollbar without distorting the content.