How to change CSS :root color variables in JavaScript
Update CSS variables on :root
with JavaScript quickly and easily. To do this, we target the document.documentElement
(the root HTML element), and use style.setProperty()
:
Here, --color-var
is your variable label, and #ff4500
is the desired color value. Swap these out as per your requirements.
JavaScript-driven theme adaptability
Persisting theme settings
Provide an enduring user experience by persisting theme settings across browser sessions using localStorage:
Effectively reapply the settings when the user returns:
Accommodating user preference
Navigate the dark mode/light mode Jedi-Sith battle using the user's preference via JavaScript's window.matchMedia()
:
Painting with broad strokes with multiple variables
When you need a bouquet of changes, you can cycle through and update multiple variables at once with JavaScript:
Making most of JavaScript: Advanced usage and potential pitfalls
Creating dynamic themes
Want to add new styles on the fly? Craft your user's experience by adding new style declarations right within the stylesheet using insertRule()
:
Reading CSS variable values
Prudently access an existing variable's value with getComputedStyle()
:
Variables with viewport
While :root
provides global access, sometimes you want to color within the lines. You can target specific elements and change their CSS variables:
In this example, the --button-hover-color
is limited to .my-button
elements.
Application of color-scheme
For an auto-magical switch between dark and light themes, lean onto the color-scheme
property:
With the color-scheme
property, the browser does all the theme lifting for you.
Was this article helpful?