/assets/css.jpg

CSS Variables

What are they?

You may know CSS preprocessors like that the good Stylus and the ugly SCSS . Each of them, as well as all the other preprocessors, has a way to keep your style sheets DRY (Don’t Repeat Yourself). One way of doing so is by using variables to reuse some code. While they’re very powerful, there is one major restriction they all face. They’re set in stone on build time in contrast, CSS variables, or CSS custom properties, are a way to influence your CSS properties at run time.

How do I use CSS Variables?

To use them you need a stylesheet. As mentioned plain CSS is all we need. They do work the same with CSS preprocessors as well. A lot of people also like to use the variables of CSS preprocessors as initial values of some CSS custom properties. We need to know how they work. So here is a list of what you can do with them and how they behave:

  • CSS variables are scoped. They only affect the style tree starting from the container they’re defined in.
  • CSS variables can be overwritten in a lower scope.
  • CSS variables are case sensitive.
  • The “strength” of a variable depends on their container (eg. id > class).
  • CSS variables can be changed on run time. So how do they look and how can they be used? Well that’s quite simple:
css
:root {
--my-variable: red;
background-color: var(--my-variable, blue);
}

As you can see CSS variables have a leading double dash (–) followed by their case sensitive name. After the variable name there follows the colon and afterwards a value. This can be anything you can assign to a CSS property.

They’re applied using the CSS var function, which works as value of a CSS variable itself. This function takes two parameters. A CSS variable, and an optional fallback value, which will be used if the variable declared first is not set.

In the following example you can see how they are used:

html
<main>
<section />
<section />
<section />
<!-- They can be added to style attributes and changed via JS -->
<section style="--primary-color: black;" />
</main>
<style>
/* defining */
main {
--primary-color: red;
--secondary-color: blue;
--tertiary-color: green;
}
section {
height: 50px;
}
/* basic assignment */
section:nth-child(1) {
background: var(--primary-color);
}
/* overwritten */
section:nth-child(2) {
--secondary-color: beige;
background: var(--secondary-color);
}
/* they can have a fallback value */
section:nth-child(3) {
background: var(--undefined-color, orange);
}
/* they're used depending on their "strengh", here it's a style attribute */
section:nth-child(4) {
--primary-color: purple;
background: var(--primary-color);
}
</style>

You can play with them within a repl:

Wrapping up

That’s all there is to CSS custom properties. They save a lot of time for color themes like dark or light mode. They might also be the right choice if you’re going for a component library, where components can be used at different positions.