CSS Variable

CSS variables (a.k.a. CSS custom properties) are declared by prefixing a property name with -- (e.g. --my-color).

You can access the variable's value using the val() function.

| LIVE PREVIEW

Lorem ipsum dolor sit amet

Concepts

Scope

CSS variables can only be used in the scope where they are declared (see example above). To make them usable anywhere (the usual practice), declare them inside :root.

Inheritance

If a variable value is not defined on the given element, the value of its parent is used.

| LIVE PREVIEW
Variable defined
Variable undefined (value inherited)
Variable undefined (use normal inherited/initial value)

CSS Functions

var(name)

Replaces this expression with the value of name.

blockquote {
  border-left: 4px solid var(--my-color);
}

var(name, fallback)

Replaces this expression with the value of name. If it's undefined or invalid, use the value of fallback.

You can use more than one fallback by nesting var(). The technique has been seen to cause performance issues as it takes more time to parse through the variables (MDN).

p.important {
  color: var(--error-color, red);
  color: var(--error-color, var(--alert-color, red));
}

References