CSS variables are great!

Jérôme Pott - Nov 29 '18 - - Dev Community

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;
}

Enter fullscreen mode Exit fullscreen mode

A new variable is declared with two dashes and can be accessed with the var() CSS function:


.main-header {
    background-color: var(--main-color);
}

Enter fullscreen mode Exit fullscreen mode

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')

Enter fullscreen mode Exit fullscreen mode

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

. . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player