CSS Variable

By Xah Lee. Date: . Last updated: .

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:

--my-color: red

Then, use it like this:

color: var(--my-color)

Here's example.

<div class="xyz">something</div>
html {
 --color-x: pink;
 --good-size: 2rem;
 --my-border: solid thin red;

color: var(--color-x);
font-size: var(--good-size);
border: var(--my-border);

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.

Browser Support

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

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.