How to style HTML5 range input to have different color before and after slider?
Nail dynamic color changes on either side of an HTML5 range input's thumb using CSS gradients and JavaScript to update the appearance. Check out this single-line solution in action:
Reliant on an inline oninput
event, the background style changes color dynamically as the slider thumb moves. Adapt the colors (green
and red
in this example) to fit your needs.
Implementing cross-browser compatibility
To consider cross-browser compatibility, we must remember that pseudo-elements for styling range inputs differ across browsers:
- WebKit-based browsers (like Chrome and Safari):
-webkit
prefix. - Firefox:
-moz
prefix. - Internet Explorer:
-ms
styling.
Building on cross-browser styling – step by step
-
Removing default styles: Start with a clean slate by dropping default styling using
-webkit-appearance: none
(also, saves your sanity, ain't nobody got time for browser defaults! 😃) -
Styling the track: For WebKit browsers, use
::-webkit-slider-runnable-track
. Similarly for Firefox,::-moz-range-track
. -
Styling the thumb: Both WebKit and Firefox have you covered –
::-webkit-slider-thumb
and::-moz-range-thumb
, respectively. -
Dynamic colors via JavaScript: Leverage JavaScript to dynamically change background based on range value. Like a chameleon, but with less sticking to ceilings.
-
Fallback for Jurassic Park browsers: Resort to a JavaScript polyfill when dealing with browsers that haven't evolved to support pseudo-elements yet (lookin' at you, IE pals!).
The devil's in the details
Watch out for the thumb size when using gradients to prevent color chopping! Smooth color transitions can be achieved using CSS transitions.
Taking special measures with styling techniques
Dialing up the pseudo-elements
For WebKit browsers, ::-webkit-slider-thumb
and ::-webkit-slider-runnable-track
will help in styling the thumb and track separately. Similarly, ::-moz-range-thumb
and ::-moz-range-track
prove handy with Firefox.
Embracing JavaScript chameleon mode
Invoke the power of JavaScript for a dynamically changing background, offering a cross-browser consistent theme.
Sprucing up with the 'accent-color' property
The accent-color
CSS property can tweak the thumb and track color, despite offering less control than other tactics.
Enhancing compatibility and appearance
Verifying browser compatibility
Before you go wild with styles, verify the browser support for the CSS properties and pseudo-elements used. Poke around websites like MDN and Can I use for an edge.
Amping up visual appearance
Boost your visual appeal beyond color using box-shadow
, border-radius
, and outline
for a truly flamboyant slider.
Was this article helpful?