Edit online

Custom CSS Properties (CSS Variables)

Custom properties (also referred to as CSS variables) are properties defined by CSS authors that contain specific values to be reused throughout a document.

Complex websites have many CSS rules, often with a lot of repeated values. For example, the same color might be used in dozens of different places, requiring a global search-and-replace operation if that color needs to be changed. Custom properties allow a value to be stored in one place, then referenced in multiple other places. An additional benefit is semantic identifiers. For example, --main-text-color is easier to understand than #00ff00, especially if this same color is also used in other contexts.

Custom properties follow the same rules as other CSS properties, so you are able to define and use them at multiple levels, following standard CSS cascading and specificity rules.

Usage

A custom property name begins with a double hyphen (--) and its value that can be any valid CSS value. You use the custom property value by specifying your custom property name inside the var() function, in place of a regular property value:

Defining a Custom Property

element {
  --main-bg-color: brown;
  background-color: var(--main-bg-color);
}
Note: Custom property names are case sensitive: --my-color will be treated as a separate custom property from --My-color.

Inheritance of Custom Properties

If you define a custom property on an element, you will be able to access it on all of its descendents.

Inheritance

<one>
  <two>
    <three/>
    <four/>
  </two>
</one>
one {
  --color:green;
}

three {
  --color:red;
}

* {
  color: var(--color);
}
Result:
  • <one> has the color green.
  • <two> has the color green.
  • <three> has the color red.
  • <four> has the color green.

Custom Properties Fallback Values

The var() function has two arguments. The first argument is the name of the custom property to be substituted. The second argument (optional) is a fallback value, which is used as the substitution value when the referenced custom property is invalid or undefined.

Specifying a Fallback Value

one {
  color: var(--color, blue);
}

one {
  color: var(--color, var(--fallback-color, red));
}

Dependencies

A custom property can reference the value of another custom property through the var() function.

A Custom Property Safely Using a Variable

:root {
  --border-color: red;
  --main-border: 1px solid var(--border-color, green);
}

p {
  border: var(--main-border);
}

Combining Custom Variables with calc()

:root {
  --foo: 10px;
  --bar: calc(var(--foo) + 10px); 
}

p {
  font-size: var(--bar);
}
CAUTION: This can create cyclic dependencies where two or more custom properties each attempt to reference each other.

An Invalid Situation of Variables Depending on Each Other

:root {
  --color:    var(--bg-color);
  --bg-color: var(--color);
}