Trusted answers to developer questions

What is a CSS variable?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

A CSS variable (also called custom property) is a variable you assign a CSS value to and reuse throughout your application. This process is identically equivalent to defining a variable in any programming language.

Basic Usage

A CSS variable is always defined by some element. The syntax is -- followed by the name of the variable. Let’s try defining one:

.element {
  --my-variable: red;
}

Using a CSS variable:

.somewhere {
  color: var(--my-variable);
}

The most important thing to realize is that when you use a CSS variable, the HTML hierarchical tree is used to evaluate it. This means that the CSS variable should be defined on or above the element you’re using it in.

A variable can take any value at all, so it’s the responsibility of the developer to use variables with compatible CSS properties.

Inheritance

One of the best features of a CSS variable, that makes it more useful than SCSS or LESS variables, is that it’s inherited.

Example:

  • HTML
  • CSS (SCSS)
  • Output

We first define --some-color at .outer, but then we redefine it at .inner, thus overriding its value under this element.

The first .foo div gets the value that was defined at .outer, while the second .foo div gets it from .inner.


This covers most of what you’ll need to know when using CSS variables. For more details, click here.

RELATED TAGS

css
scss
less
Did you find this helpful?