CSS Variables (Custom Properties)

Coralie Mycek
Jul 26, 2017 · 1 min read

I watched the talk of Guil Hernandez from CSSconf EU 2017. I found out that CSS variables work really easily and are a powerful tool.

A simple example

To set a variable’s value:

To retrieve the variable’s value:

To see it in action, look at this CodePen:

CSS variables need to be defined within a scope. :root is a pseudo class that represents the <html> element. It is the top level scope. Let’s see what we can do with scopes.

An example using scopes

The variable can be overridden in a different scope. For example, in this code the variable ‘color’ is ‘blue’ in the class ‘.wrapper’ and ‘red’ everywhere else:

Javascript example

The advantage of CSS variables, compared to Sass or Less variables, which are precompiled, is that the variable can be changed on the fly. You can for instance change a variable from your javascript code:

<DOM element>.style.setProperty(‘ <var name>’, ‘<var value>’);

Wrapping up

CSS variables are globally supported at 72.16% by browsers:

http://caniuse.com/#feat=css-variables

Thanks for reading this article. CSS offers lots of new features; let me know in the comments if you would like me to post again on this topic.

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Coralie Mycek

Written by

I am a frontend developer working mainly for the new program of flyingblue.com that has been released on April, 1st.

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade