CSS Variables (Custom Properties)
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:
<DOM element>.style.setProperty(‘ <var name>’, ‘<var value>’);
CSS variables are globally supported at 72.16% by browsers:
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.