DEV Community

Cover image for Harnessing The Power Of CSS Variables With JavaScript
Abdulqudus Abubakre
Abdulqudus Abubakre

Posted on • Updated on

Harnessing The Power Of CSS Variables With JavaScript

CSS Variables have been around for quite some time now and I have to say, it has been really helpful. Prior to the introduction of CSS variables, frontend developers might opt for CSS pre-processors like LESS, SASS and Stylus. But what exactly are CSS variables??

Just the way you declare variables in JavaScript, java, python or whatever language you code in, CSS variables is just that. It allows you to store values you would otherwise have to repeat throughout your code. This can be particularly painful when you're building a very large app.

How does it work?

Quite simple actually. Say the primary color for your website is #414FF6 and you want to save that color as a variable, here's how you'd go about it.

--primary: #414FF6;
Enter fullscreen mode Exit fullscreen mode

Pretty straightforward right? And just like variables in programming languages, CSS variables can also be scoped. To create a variable that would be accessible throughout your website, all you need to do is declare the variable within the :root block

:root {
    --primary: #414FF6;
}
Enter fullscreen mode Exit fullscreen mode

Likewise to make the variable local, you just need to add the variable within that CSS block. So declaring the --primary variable within a .container class and all elements under the .container element would be able to access the variable

.container {
    --primary: #414FF6;
}
Enter fullscreen mode Exit fullscreen mode

Using CSS variables

Declaring CSS variables was quite easy, well using these variables is just as easy. To use the --primary variable code we declared earlier, all we need to do is wrap in var(). Here's how that would look.

:root {
    --primary: #414FF6;
}

.btn-primary {
    background-color: var(--primary);
    color: #fff;
}
Enter fullscreen mode Exit fullscreen mode

Browser Fallback

While most major browsers support CSS variables, there are some browsers that don't. To fix that, we simple provide a fallback value for our variable. For example,

.btn-primary {
    background-color: blue;
    background-color: var(--primary);
    color: #fff;
}
Enter fullscreen mode Exit fullscreen mode

For browsers that support CSS variables, the color would be #414FF6, while browsers that don't support them would render a blue color.

Just like that, we've been able to declare and use our CSS variables.

Manipulating CSS variables in JavaScript

Now to the JavaScript part. When variables are declared in other CSS pre-processors, we usually don't have direct access to them (though there are workarounds), but With CSS variables, we have direct access to them in our JavaScript and we can easily manipulate the value of the variables using the setProperty method.
Here's a simple JavaScript snippet that changes the value of our --primary on button click.

const root = document.documentElement;
const toggle = () => {
  root.style.setProperty('--primary', 'red');
}
Enter fullscreen mode Exit fullscreen mode

In the first line, we're selecting the root element because our variable was declared within the :root block. If it was declared locally within the .container block, we'd simply select the element using querySelector or any other preferred selector of your choice.
The toggle function basically sets the --primary variable to red. So now our button, and any other element on the page that uses our variable should have the red color.

To get the value of a variable, there are two ways to go about that. Using the getComputedStyle or style.getPropertyValue

const root = document.documentElement;
const value = root.style.getPropertyValue('--primary');
// or
const valueTwo = getComputedStyle(root).getPropertyValue('--primary') 
Enter fullscreen mode Exit fullscreen mode

Here's a codepen link where I'm changing the background color of a circle on the click of a button using CSS variables.

And that's it. We've been able to create, use and manipulate CSS variables with JavaScript.
One thing to note though, CSS variables are case sensitive so --primary-color and --Primary-Color are two different variables.

Top comments (15)

Collapse
 
galaxy4public profile image
(GalaxyMaster)

The fallback for older browsers is misrepresented here. The construct presented here, var(--variable, default), is for when a variable is undefined. The fallback for older browsers that do not support variables would be defining the same attribute without a call to var() before a more modern definition, so the cascade will take care of unknown value by respecting the prior definition.

Collapse
 
ibn_abubakre profile image
Abdulqudus Abubakre

oh wow, thanks for the correction

Collapse
 
favouritejome profile image
Favourite Jome

Thanks for the hint, based on the post I was able to make a linear gradient change.

Collapse
 
ibn_abubakre profile image
Abdulqudus Abubakre

haha...nice. Would love to see it

Collapse
 
favouritejome profile image
Favourite Jome

Do you mean the code?

Thread Thread
 
ibn_abubakre profile image
Abdulqudus Abubakre

Just the implementation. I think I've seen it on Twitter. Nice work man 💪🏻💪🏻

Thread Thread
 
favouritejome profile image
Favourite Jome

Yh

Collapse
 
kennielarkson profile image
LAWAL ABDULRAFIU KEHINDE

This was a very straightforward tutorial on CSS variables.
Just all that is needed to start using the technology.
I’m glad I read this.
Good read.

Collapse
 
timothyokooboh profile image
timothyokooboh

Very nice article. Easy to understand.

Collapse
 
cepreu5 profile image
cepreu5 • Edited

Don't insert a space between var and ( as var (--primary) will not work while var(--primary) will.

Collapse
 
cdsaenz profile image
Charly S.

Great article thanks!

Collapse
 
20nick06 profile image
Nick

Awesome article thanks for the information

Collapse
 
damilolaaaron profile image
dAMi

Nice article

Collapse
 
souksyp profile image
Souk Syp.

Would that work with multiple css files ?

Collapse
 
vaaski profile image
vaaski

pretty sure, yes