I moved to backend development more than a decade ago and returning to webdesign is wild. Turns out features I would have sold my soul for back in the 00’s actually exist now. Like the
calc() function, the
aspect-ratio property, and COLRv1 fonts.
But css variables are my new favorite thing.
But what are those?
Variables store values, and can be accessed in other parts of your stylesheet, to apply said values to various elements.
Instead of finding and replacing a color, font, etc. everywhere you used it, you can instead define it in one place and change it there.
You can declare your variables inside a selector.
The simplest way to do it is to use the
:root selector, which will make the variables accessible globally.
You can then call that variable in other selectors, using the
var() function, like this:
Variables in action
Let’s make a very, very simple example with minimal html.
That isn’t very fancy, so let’s give it a makeover. In our css file, let’s define the variables we will need: colors, a border radius…
And then, let’s use the variables in our selectors.
And here we are. Behold, our fancy block:
And now we switch themes!
CSS variables can be redefined inside selectors, which allows for quite a bit of customisation with minimal code.
You don’t have to redefine every variable. You can do this:
Or you can do this:
It makes everything easier.
Want a day/night theme? Change the colors. Change the images. Want to make things a bit easier on your dyslexic visitors? Change the fonts, the line height and letter spacing. Or you can just be creative and have a custom design by page.
Theme switching demo