How to Update a CSS Variable Using JavaScript?

Using the style.setProperty() method we can override/update global or local scoped CSS variables. It has the following syntax:

style.setProperty(propertyName, value, priority);

Where propertyName in our case would be the CSS variable we wish to update, and the value would be whatever we want the new value to be. Optionally, you can specify the third argument as well to set the priority (e.g. important, undefined or an empty string).

style.setProperty() works by setting the property inline on the style attribute of an element, and since CSS rules set via the style attribute have the highest specificity in CSS, it would overwrite other rules.

Updating Global Scoped CSS Variables

Global scoped CSS variables are typically set on the :root pseudo-class (e.g. the <html> element in an HTML document), like so:

:root {
    --color-background: white;
}

We can set the same rule on the <html> element tag as well since it is the "root" element in an HTML document (i.e. all the elements in an HTML document are enclosed within the <html> element). However, be mindful of the fact that in other types of documents (such as RSS, etc.) the root element would differ.

We can update any global scoped variable using JavaScript like so:

document.documentElement.style.setProperty('--color-background', 'black');

In an HTML document, for example, this would result in:

<html style="--color-background:black;">

Updating Local Scoped CSS Variables

A CSS variable can be declared within any selector. The selector in which the variable is declared defines the scope that the variable can be used in. For example, let's suppose we have the following style rules and markup:

:root {
    --color-background: white;
}

#footer {
    --color-background: pink;
}

p {
    background-color: var(--color-background);
}
<div id="body">
    <p>body</p>
</div>

<div id="footer">
    <p>footer</p>
</div>

This would mean that using the "--color-background" variable within the element <div id="footer"> (including its children) would have the color pink while using it elsewhere within the document would have the color white (since it's declared in the global scope).

To change the locally scoped variable using JavaScript we can do the following, for example:

document.getElementById('footer').style.setProperty('--color-background', 'blue');

This would result in:

<div id="body">
    <p>body</p>
</div>

<div id="footer" style="--color-background:blue;">
    <p>footer</p>
</div>

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.