Search⌘ K
AI Features

Custom Properties (Variables)

Explore how CSS custom properties (variables) improve web styling by reducing repetition and enabling scoped values. Gain skills to define variables globally and locally, use them in calculations and media queries, and apply fallback values for flexible, maintainable CSS.

CSS Variables

Custom properties (commonly known as CSS Variables) are a modern addition to CSS. If you’ve worked with programming languages such as JavaScript or Python, you’ll know that variables are extremely useful.

A variable is a name that refers to a value. By using variables in CSS, we greatly reduce code repetition and create style sheets that are much easier to maintain.

Defining a CSS variable

We define a variable by using a name that begins with a double hyphen followed by a colon and any valid CSS value. For example, we have the --primary-color: variable set to green in the code below:

:root {
  --primary-color: green;
}

The :root pseudo-class is a special selector that globally applies the HTML document’s style. More on this later!

The variable can ...