Skip to main content Accessibility Feedback

CSS variables

Yesterday, I mentioned that I love CSS variables. Today, I thought I’d explain what they are and how they work, for those who aren’t already familiar with them.

Let’s dig in!

How to define CSS variables

You define a CSS variable by typing its name with a leading double-dash (--).

It uses the same syntax a typical CSS property—--{name}: {value}—and must be defined on an element.

p {
	--size: 1rem;
}

You can then use your CSS variable just like you would any other property value by wrapping it in var().

CSS variables have to be defined on the element they’re being used on or a parent of that element (they inherit just like all other things CSS).

p {
	--size: 1rem;
	font-size: var(--size);
}

You’re probably thinking: this seems like more work to do the same thing.

You’re right… in this specific example. Let’s look at how to make CSS variables more useful.

Global CSS variables

One common approach to working with CSS variables is define a bunch of global variables on the :root element.

This typically includes things like colors, sizes, and typefaces.

:root {

	/* Colors */
	--color-primary: #0088cc;
	--color-secondary: rebeccapurple;
	--color-black: #272727;
	--color-white: #ffffff;

	/* Sizes */
	--size-default: 1rem;
	--size-small: 0.875rem;
	--size-large: 1.25rem;

	/* Typefaces */
	--font-sans: "PT Sans", sans;
	--font-serif: "PT Serif", serif;
	--font-mono: Menlo, Monaco, "Courier New", monospace;

}

Because the :root is the top-level element of the DOM, you can use these in anywhere else in your stylesheet.

p {
	font-size: var(--size-default);
}

a {
	color: var(--color-primary);
}

button {
	background-color: var(--color-primary);
	border: 1px solid var(--color-primary);
	color: var(--color-white);
	font-size: var(--size-default);
}

button:hover {
	background-color: var(--color-secondary);
	border: 1px solid var(--color-secondary);
}

Unlike the first example, they can now be reused, which makes them far more functional. And if you need to change an aspect of your design system—like a color or typeface—you update a single value and have it change everywhere.

Here’s a demo.

Tomorrow, I’m going to share a technique for using CSS variables that reduces the amount of redeclared variables you need to use and puts the power of the cascade to full effect.