CSS: Variable (Custom Property)

By Xah Lee. Date: . Last updated: .

What is CSS Custom Property

CSS allows you you use variable. This is called CSS Custom Property.

Declare variable like a property, but with the property name with prefix of 2 hyphens, like this:

--x: red

Then, use it like this:

color: var(--x)

There must be no space after var.

Technically, CSS variable is called a CSS custom property. You should think of it as custom property, because, it is used just like properties, with the same cascading precedence for their scope, and overwriting a value is also the same as CSS cascade.

Example

<div class="xyz">something</div>
:root {
 --xx: pink;
 --yy: 30px;
 --zz: solid thin red;
}

div.xyz
{
color: var(--xx);
font-size: var(--yy);
border: var(--zz);
}

The :root means root of the HTML or XML.

Variable Chaining

Values can be a variable declared previously.

:root {
 --x-col:pink;
 --x-pane-border:solid 3px var(--x-col);
}

Browser Support

CSS custom property is supported by all major browsers since 2017-01, except Internet Explorer.

CSS, Advanced