Explain Codes LogoExplain Codes Logo

How can I style horizontal scrollbar by CSS?

html
responsive-design
css3-pseudo-selectors
accessibility
Anton ShumikhinbyAnton Shumikhin·Nov 3, 2024
TLDR

Immediately style a horizontal scrollbar in Chrome and Safari with ::-webkit-scrollbar pseudo-elements:

/* Adjust scrollbar track - don't be a slacker, track it up */ ::-webkit-scrollbar { height: 10px; background: #f2f2f2; } /* Style scrollbar handle - because handles also need some loving */ ::-webkit-scrollbar-thumb { background: #888; border-radius: 5px; }

When targeting all browsers, consider a JavaScript scrollbar library.

Beyond basics: enhancing UX with styled scrollbar

Customized scrollbars can complement your site's aesthetics, provided they don't become disruptive.

  • Use media queries to tailor scrollbar styles to various screen sizes.
  • Control scrollbar visibility with the overflow property.

Handle with care: cross-browser compatibility

::-webkit-scrollbar is not supported universally. Other lookup selections are CSS3 pseudo-selectors or JavaScript libraries like Perfect Scrollbar.

  • ::-webkit-scrollbar functions on Chrome, Safari, and updated Edge versions.
  • Firefox allows using scrollbar-color and scrollbar-width properties.
  • Universal compatibility still leans towards a JavaScript solution.

Dealing with the state of native scrollbar styling

The W3C CSS Scrollbar Module Level 1 standardizes scrollbar styles across browsers. However, it's crucial to remember that scouting caniuse.com and staying updated on the current state of scrollbar support is helpful.

Advanced techniques: better control

Dynamic scrollbars change colors when hovered over or scrolling. The border property can add a whole new level of color and style. Experiment with pseudos, like ::-webkit-scrollbar-button.

Prioritizing accessibility

When styling scrollbars, keeping accessibility in mind is key. Ensure enough contrast between the thumb and the track., and remember that a larger scrollbar can aid users with motor impairments.

Optimization tips: performance & aesthetics

Maintaining performance and aesthetic appeal often boils down to:

  • Using CSS whenever possible.
  • Ensuring extensive testing.
  • Using optimized images, if any.