Declaring a new variable
You can define CSS variables anywhere in your stylesheets, but you usually want to have them declared in the root element of the document. By doing so, you can access them globally.
:root {
--main-color: blue;
}
A new variable is declared with two dashes and can be accessed with the var()
CSS function:
.main-header {
background-color: var(--main-color);
}
Yes, coming from SASS, the syntax may look quite strange to you. It will take some getting used to.
Updating the value with JavaScript
Here lies the true strength of CSS variables: they can be changed at runtime, unlike SASS variables which are compiled down to regular CSS.
Here is how to update a CSS variable:
document.documentElement.style.setProperty('--main-color', 'green')
Now all properties containing that variable will have their value set to 'green'.
A real-word example
Recently I have been working on a small Nuxt.js application in which I needed to pass a value (a HEX color code) between two components on different routes. The HEX color was supposed to change the background color of the header and the footer.
Using event emitters was not possible because of the routing, and the addition of a state management library felt like an overkill.
💡 My solution
I declared a CSS variable on the root element and had the component update its value. Since the other component relied on the same variable, its value was also updated.
Link to the specific line on GitHub: https://github.com/mornir/copywork-portfolio/blob/master/pages/_slug.vue#L109
Link to the website: copywork.surge.sh
Top comments (8)
Wait, so what's the browser compatibility with this?
As much as I love SCSS, and I do, if I don't have to use it anymore in place of standard css, that's ideal
CSS variables are supported in all modern browsers.
For Internet Explorer, I usually use a fallback value:
But then, of course, updating value at runtime won't work in IE. I think that this fallback is sufficient when the changes are only cosmetic.
For Internet Explorer, you can try this polyfill:
github.com/nuxodin/ie11CustomPrope...
It enables nearly full custom properties support for it.
Support is not too shabby: developer.mozilla.org/en-US/docs/W...
That's support for setProperty itself, not support for cash variables, which won't work with setProperty (or at all on ie without polyfilling - and the best polfyills only support initial evaluation)
caniuse.com/#feat=css-variables
So, aside from IE, if your browser is less than a year old (2 years, at least, if you exclude Edge), CSS variables work.
I didn't know this was a thing. Thanks!
I was not aware of this trick too, great article !