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.

Declaring variables

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.

:root {
    --my-color: #fff;

You can then call that variable in other selectors, using the var() function, like this:

.my-class {
    color: var(--my-color);

Variables in action

Let’s make a very, very simple example with minimal html.

<div class="tut-demo">
    <div>My fancy content</div>

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…

:root {
    --tut-bg-primary: #fff;
    --tut-bg-secondary: #8f0b42;
    --tut-color-primary: #17181c;
    --tut-color-secondary: #fff;
    --tut-border-radius: 20px;

And then, let’s use the variables in our selectors.

.tut-demo {
    background: var(--tut-bg-primary);
    color: var(--tut-color-primary);
    border-radius: calc(var(--tut-border-radius) * 1.5);
    border: 2px solid var(--tut-bg-secondary);

.tut-demo header {
    border-radius: var(--tut-border-radius);
    background: var(--tut-bg-secondary);
    color: var(--tut-color-secondary);

And here we are. Behold, our fancy block:

My fancy content

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:

.tut-demo-blue {
    --tut-bg-secondary: #3d9bbd;
<div class="tut-demo tut-demo-blue">
My fancy content

Or you can do this:

.tut-demo-yellow {
    --tut-bg-primary: #3f3f3f;
    --tut-bg-secondary: #ffc771;
    --tut-color-primary: #ffffff;
    --tut-color-secondary: #000000;
    --tut-border-radius: 0px;
<div class="tut-demo tut-demo-yellow">
My fancy content

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

My fancy content