Newsletter

CSS variables tutorial: declare, scope and use custom properties

CSS variables tutorial: declare, scope and use custom properties

CSS Custom Properties, better known as CSS variables, are a real step forward for front-end developers. They bring the power of variables to CSS, which means less repetition, better readability and more flexibility.

On top of that, unlike the variables of CSS preprocessors, CSS variables are part of the DOM, and that brings a number of benefits. They are essentially the equivalent of SASS and LESS variables. In this tutorial I will walk you through examples of how this CSS3 module works.

Why use CSS variables?

There are plenty of reasons to use variables in CSS. One of the most convincing is that they cut down the repetition in your stylesheet.

The old way

css
#title {
    color: #ff0000;
}

.h1 {
    color: #ff0000;
}

The new way

css
:root {
    --red: #ff0000; /* Déclaration d'une variable css */
}
#title {
    color: var(--red); /* Utilisation de la variable css */
}

.h1 {
    color: var(--red); /* Utilisation de la variable css */
}

Not only does this make your code easier to read, it also gives you far more flexibility the day you want to change that colour.

All of which has been possible with SASS and LESS variables for years. CSS variables, though, come with a couple of extra advantages.

  1. They do not need to be compiled to work, since the browser handles them natively. So there is no setup to get started, unlike SASS and LESS
  2. They live in the DOM, which opens up a whole set of possibilities that I will go through in this tutorial.

Let us get started with CSS variables.

Declaring your first CSS variable

To declare a variable, you first have to decide which scope it should live in. If you want it available everywhere, simply define it on the :root pseudo-class. It matches the root element of your document tree, in other words the <html> tag.

Since variables are inherited, that makes your variable available throughout your whole application, because every DOM element is a descendant of the <html> tag.

css
:root {
    --main-color: #00FF00; /* Déclaration d'une variable css */
}

As you can see, you declare a variable exactly the way you set a CSS property. The name simply has to start with two dashes.

To read a variable, use the var() function and pass the name of the variable as its argument.

css
#title {
  color: var(--main-color);
}

And that gives your heading the colour #00FF00.

Declaring a local CSS variable

You can also create local variables, which are only reachable from the element they are declared on and from its children. That is useful when you know a variable will only ever be used in one or two specific parts of your application.

For instance, you might have an alert box that uses a particular colour used nowhere else in the application. In that case, declaring it locally makes sense.

css
.alert {
  --alert-color: #ff0000;
}

The variable can now be used by the children of that element:

css
.alert p {
  color: var(--alert-color);
  border: 1px solid var(--alert-color);
}

If you try to use the alert-color variable somewhere else in your application, in the navigation bar for example, nothing happens. The browser simply ignores that line of CSS.

Responsive design with CSS variables

A big advantage of CSS variables is that they have access to the DOM. That is not the case with LESS or SASS, whose variables are compiled to CSS before the browser ever reads them

In practice, it means you can change a variable depending on the width of the screen, for example:

css
:root {
  --main-size: 16px ;
}
@media all and (max-width: 600px) {
  :root {
    --main-size : 12px ;
  }
}

And with those four simple lines of code, you have updated the main font size across your entire application when it is displayed on small screens. Rather elegant, is it not?

Reading CSS variables from JavaScript

Another benefit of living in the DOM is that you can read the variables from JavaScript, and even update them, in response to user interaction for instance.

javascript
var root = document.querySelector(':root') ;
var rootStyles = getComputedStyle(root) ;
var mainColor = rootStyles.getPropertyValue('--main-color') ;
console.log(mainColor); // #00FF00

To update a CSS variable, call the setProperty method on the element the CSS variables were declared on, passing the name of the variable as the first argument and the new value as the second.

javascript
root.style.setProperty('--main-color','#0000ff')

Browser support

tutoriel-variables-css.jpeg

Every current browser supports CSS variables, only Internet Explorer, now discontinued, ignores them.

···

CSS

Damien Flandrin Web developer since 2010, creator of Gekkode and Email Impact. Every article is tested on a real project before publication. Contact
Newsletter

New tests, tutorials and projects, by e-mail.

Reproducible tests, versioned code, dated results. Never any spam.