Explain Codes LogoExplain Codes Logo

How to change CSS :root color variables in JavaScript

javascript
prompt-engineering
functions
getcomputedstyle
Nikita BarsukovbyNikita Barsukov·Feb 15, 2025
TLDR

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():

// Banish the gloom - brightness incoming with `--color-var` set to '#ff4500' document.documentElement.style.setProperty('--color-var', '#ff4500');

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:

// Sunshine mode on! Set a new value for --color-var and sear it into localStorage const newColor = '#ff4500'; document.documentElement.style.setProperty('--color-var', newColor); localStorage.setItem('themeColor', newColor);

Effectively reapply the settings when the user returns:

// Welcome back, human! Your preferred theme, as you left it: const savedColor = localStorage.getItem('themeColor'); if (savedColor) { document.documentElement.style.setProperty('--color-var', savedColor); }

Accommodating user preference

Navigate the dark mode/light mode Jedi-Sith battle using the user's preference via JavaScript's window.matchMedia():

// A person is smart; people are dumb. But they all like themes. Dark or light? if (window.matchMedia('(prefers-color-scheme: dark)').matches) { // Light a candle for the dark side document.documentElement.style.setProperty('--background-color', '#333'); document.documentElement.style.setProperty('--text-color', '#fff'); } else { // It's a sunny day! Every. Single. Day. document.documentElement.style.setProperty('--background-color', '#fff'); document.documentElement.style.setProperty('--text-color', '#333'); }

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:

const themeColors = { '--background-color': '#282c34', '--text-color': '#f7f7f7', '--highlight-color': '#ff4081' }; // Fancy a change of scene? En masse! Object.entries(themeColors).forEach(([key, value]) => { document.documentElement.style.setProperty(key, value); });

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():

// Abra-ca-dabra! New style, comin' right up! const newStyle = '--new-theme-color: #4a90e2;'; document.styleSheets[0].insertRule(`:root { ${newStyle} }`, 0);

Reading CSS variable values

Prudently access an existing variable's value with getComputedStyle():

// Spy mode ON. Procuring color intel: const rootStyles = getComputedStyle(document.documentElement); const mainColor = rootStyles.getPropertyValue('--main-color').trim(); // Now, you're in on the secret. mainColor holds the value of --main-color

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:

let button = document.querySelector('.my-button'); button.style.setProperty('--button-hover-color', '#FF6347');

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:

:root { color-scheme: light dark; }

With the color-scheme property, the browser does all the theme lifting for you.