CSS Variables! They’re finally available and supported in all browsers – Yeay! 🎉… Well almost all. According to Caniuse, they’re currently available on all major browsers except IE as well as on all mobile browsers except Opera Mini.
What are CSS Variables?
CSS Variables allow the use of, well… variables in CSS without need for pre-processors. As developers, we know that as web projects grow bigger, it becomes more difficult to maintain large and often times messy CSS. Variables also gives us the ability to reuse and easily edit repeatedly occurring CSS properties. Although that has been achievable, to an extent, with Sass, Less and other extensions, they have been pre-processors, which require compiling before use. Variables, however, can be used right away in your browser.
Setting and Using CSS Variables
Why are CSS Variables useful?
CSS Variables are potentially very useful; presenting opportunities to make our CSS more efficient as well as maintainable and in this post, I outline some of the reasons why you should explore and consider using them.
1. Change dynamically
Variables are dynamic. They can change at runtime, allowing for scoping to elements and overriding as required. On changing a variable, the lowermost definition in the stylesheet overwrites the ones above it; following standard cascade rules.
Variable, once defined, can be used repeatedly. For example, for a colour that might be used in hundreds of different places, CSS variables allow the value to be stored in one place, then referenced in multiple other places. If the colour needs to be updated, the change is made in only one place, rather that searching and replacing the hundreds of different places.
Mutiple fallback values can be defined, which will be used when the given variable is not yet defined.
color: var(--my-var, red); /* Red if --my-var is not defined */
background-color: var(--my-var, var(--my-background, pink)); /* pink if my-var and --my-background are not defined */
background-color: var(--my-var, --my-background, pink); /* Invalid: "--my-background, pink" */
// get variable from inline style
// get variable from wherever
// set variable on inline style
element.style.setProperty("--my-var", jsVar + 4);
9. Case sensitive
Variables (custom properties) are case sensitive, so --header-color and --Header-Color are different
Allows for complex calculations; again, presenting great potential.
--foo: if(x > 5) this.width = 10;
BONUS* – CSS Variable Demo
A quick demo to display use of CSS Variables in action. This allows the use of variables in CSS without need for pre-processors. It is currently available on all major browser except IE and all mobile browsers except Opera Mini.