How to Create and Update CSS Variables Dynamically with JavaScript

By w3iscool, April 8, 2023

CSS variables, also known as custom properties, are a powerful feature that allows you to define and reuse values in your stylesheets. They can help you create more consistent, maintainable, and adaptable designs.

However, CSS variables are not very dynamic by default. They are usually declared in the :root selector or in a specific scope, and their values are fixed unless you use media queries or other CSS features to change them.

But what if you want to change the values of CSS variables dynamically with JavaScript? For example, you might want to let the user choose a theme for your website, or you might want to update the colors based on some data.

In this post, we will show you how to create a style node and update root CSS variables dynamically with JavaScript. This way, you can have more control and flexibility over your CSS variables and create more interactive and responsive designs.

Creating a Style Node with CSS Variables

The first step is to create a style element and append it to the head of the document. This style element will contain the CSS rules that use the variables we want to update.

To create a style element, we can use the document.createElement() method and set its type attribute to “text/css”. Then, we can use the style.innerHTML property to set the CSS rules with variables in the style element.

For example, let’s say we want to create four variables for the main color, hover color, body color, and box color of our website. We can use the following code:

javascript

// Create a style element
var style = document.createElement('style');
style.type = 'text/css';

// Set the CSS rules with variables
style.innerHTML = `
:root {
  --main-color: #317EEB;
  --hover-color: #2764BA;
  --body-color: #E0E0E0;
  --box-color: white;
}

body {
  background-color: var(--body-color);
}

div {
  background-color: var(--main-color);
  color: var(--box-color);
}

div:hover {
  background-color: var(--hover-color);
}
`;

// Append the style element to the head
document.getElementsByTagName('head')[0].appendChild(style);
This code will create a style element like this:

html

And it will apply the styles to our HTML elements like this:

Example of HTML elements styled with CSS variables

Updating CSS Variables with JavaScript

The next step is to update the values of the CSS variables with JavaScript. To do this, we can use the document.documentElement.style.setProperty() method.

This method allows us to set or override a CSS property value on an element. It has the following syntax:

javascript
element.style.setProperty(propertyName, value, priority);

Where propertyName in our case would be the CSS variable we wish to update, and value would be whatever we want the new value to be. The priority parameter is optional and can be used to specify if the property should have an "important" flag or not.

For example, let's say we want to change the main color and hover color of our website to black and red respectively. We can use the following code:

javascript

// Update the values of the variables
document.documentElement.style.setProperty('--main-color', '#000000');
document.documentElement.style.setProperty('--hover-color', '#FF0000');

This code will update the values of the –main-color and –hover-color variables in the :root scope. As a result, the styles of our HTML elements will change accordingly:

Example of HTML elements styled with updated CSS variables

We can also use this method to update the values of CSS variables in other scopes, such as classes or ids. For example, let’s say we have a class called .special that uses a different variable for its background color:

css

.special {
--special-color: green;
background-color: var(--special-color);
}
We can update the value of this variable by selecting the element with this class and using the setProperty() method on it:

javascript

// Select the element with the .special class
var special = document.querySelector('.special');

// Update the value of the variable
special.style.setProperty('--special-color', 'purple');

This code will change the background color of the element with the .special class to purple:

Conclusion

In this post, we have learned how to create a style node and update root CSS variables dynamically with JavaScript. This technique can help us create more dynamic and interactive designs that can respond to user input, data changes, or other events.

We have also seen how to update CSS variables in other scopes, such as classes or ids. However, we should be careful not to create too many variables or scopes, as this can make our code harder to maintain and debug.

CSS variables are a powerful and useful feature that can enhance our web development experience. We hope you have found this post helpful and informative. If you have any questions or feedback, please let us know in the comments below. Thank you for reading!

DEMO

Please follow on facebook.

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *