Variables

Also known as CSS Custom Properties, variables allow you to create a named value that can be reused throughout your CSS, similar to how letters stand in for numbers in algebraic variables.

Defining Variables

Variable names must be prefixed with two dashes: --, and they can be written like ordinary CSS declarations: --variable-name: #eee; They should be defined within an element and can only be used on elements that are children of the element in which they are defined. For variables you wish to use throughout your CSS, define them using html as the selector. (You sometimes also see :root used as a selector for global variables. This is the same as using html.)

Defining a variable that can be used anywhere in the CSS

Defining a variable that can only be used in the site header

Redefining and Overriding

As with any normal CSS property, variable definitions can be overriden by redeclaring them later in the document or on a selector with higher specificity. All instances of the variable in use will reflect the new value.

A common use for this might be with media queries:

You might also use this to create component-specific overrides:

Using Variables

Variables can be used in place of a relevant value by expressing the name within the parinthesis of var().

Video Lesson

The following video demo is fully interactive. You can pause at any time to directly edit the code, and resume playback to restore to where you left off.