How do we set and change CSS custom properties (aka CSS variables) with JavaScript?
A modern CSS file often starts with something like this:
:root {
--color: #ddd;
--link-color: var(--btn-color);
--accent-color: goldenrod;
--bgc: #25c;
--btn-color: #a15583;
--btn-active: rgb(202, 173, 5);
--bg-img: radial-gradient(circle at 30% -5%, white 5%, black 100%);
--max-width: 1100px;
}
JavaScript comes with several methods to change these custom properties:
setProperty()
removeProperty()
getPropertyValue()
You can access the :root
element in the usual way:
const root = document.querySelector(':root');
Example code
The following code is used to set the value of the --main-bg
custom property in the :root
element from an input type="range"
slider element.
Whenever the slider is changed an event listener runs an arrow function which changes the number at the end of the slider and the value of the --main-hue
custom property in the CSS.
const root = document.querySelector(':root');
const bgHueSlider = document.querySelector('#bg-hue-slider');
const hueNumBox = document.querySelector('.hue-num-box');
bgHueSlider.addEventListener('input', () => {
hueNumBox.textContent = bgHueSlider.value;
root.style.setProperty('--main-hue', bgHueSlider.value )
});
Change the background hue
Links
- Scrimba video on Youtube.