Variables

Variables

CSS variables are custom properties that are defined in one place and used in multiple places throughout the stylesheet.

Syntax

CSS variables are used in two principle steps:

  1. Define the custom variable inside a selected element

    Loading...
  2. Use the var() function to allow --custom-variable to be assigned to a property in multiple elements:

    Loading...

CSS Variables and the Cascade

CSS cascade rules makes custom variable properties inheritable. This means that any child or grandchild element can inherit that variable value.

In the samples below, there are 3 div elements with classes divA, divB, and divC. The hierarchy is as follows:

  • divA is the topmost parent in the body
  • divB is a child of divA
  • divC is a child of divB (and a grand-child of divA)
Loading...

The CSS variable --custom-bg-color-saffron is defined in the selector for divB.

Loading...

The rendered image below shows that the background color for divB is set to --custom-bg-color-saffron. While its child, divC, doesn’t have background color specified, it inherits the property from its parent. On the other hand, divA, the parent of divB, has a default white background color because it exists outside the scope of --custom-bg-color-saffron.

Image of cascading divs using CSS variables for background color

Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn CSS on Codecademy