CSS: Variable (custom property)

By Xah Lee. Date: . Last updated: .

What is CSS Custom Property

CSS allows you you define variables. This is called CSS Custom Property.

Declare variable like a property, but the name must start with 2 hyphens.

/* example of css custom property */
body {
 --my-color: pink;
}

to use the variable value, use var(var-name, fall-back-value).

.x {
 /* using css variable. */
 color: var(--my-color);
}

🛑 WARNING: There must be no space after var.

Example

/* declare several variables, valid at root node and all its children */
:root {
 --my-color: pink;
 --main-fontsize: 1.5rem;
 --border-val: solid thin red;
}

.x {
 /* using the variable */
 color: var(--my-color);

 font-size: var(--main-fontsize);

 /* if --border-val is not defined, use fallback */
 border: var(--border-val, solid 1px grey);

 /* other */
 margin: 1rem;
}

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 special property and values