Custom properties

What are custom properties?

Custom properties or CSS variables allow you to define a value once and reuse it in multiple places. They are especially useful for defining design tokens, such as font sizes, colors, and spacing.

Syntax and usage

To define a custom property, you use the -- prefix, and then the name of the property in kebab-case. The name of the property is then followed by a value, which can be any valid CSS value. We suggest declaring custom properties in the :root pseudo-class, which contains all elements on the page, rendering the variable accessible everywhere.

:root {
  --font-size: .75rem;
  --font-size-headings: 1.5rem;
  --line-height: 1.5;
  --color-primary: deeppink;
}

To use a custom property, you use the var() function, followed by the name of the property in kebab-case. You can also set a fallback value, which will be used if the custom property is not defined.

body {
  font-size: var(--font-size, 1rem);
  line-height: var(--line-height, 1.5);
  color: var(--color-primary, blue);
}

h1, h2, h3, h4, h5, h6 {
  font-size: var(--font-size-headings, 1.5rem);
}
Advanced: variable oriented CSS

The use of custom properties is not limited to the :root pseudo-element and typography. You can use them to define variables for any part of your CSS, such as border-radius, box-shadow, and transitions.