Introduction to CSS Variables — Part 2
In my previous post, I discussed some basics of CSS variables. But one question is still unanswered: What can CSS variables do?
For example, if I have a variable with color value, where can I use that variable? We’ve already seen color variables applied to color
and background-color
styles. Where else could you use them?
- Border-color: Yes
- Box-shadow color: Yes
- Pseudo classes such as
:hover
or:focus
: Yes - Pseudo elements
::before
and::after
: Yes
Essentially you can use these variables in any style declaration that accepts a color!
The image to comes from a CodePen. You can fiddle with it here.
Of course, if you have worked with CSS preprocessors, such as Sass or Less, you might fail to see why these variables are useful. After all, these preprocessors come loaded with their own variables (see Sass and Less variables). For me, it boils down to two facts:
- You can change the value of CSS variables in browser (using Javascript), whereas you can’t do the same for preprocessor variables.
- Unlike preprocessor variables, CSS variables cascade. So, if I changed the value of a particular variable under a
div
element, all its descendants are going to inherit the value from thediv
rather than theroot
element.
So next time, we will discuss how you could change the values of CSS variables in browser, and how your app can benefit from such a feature.