Custom Properties (CSS Variables)

Store reusable values like colors and spacing in variables to build flexible, scalable themes.

CSS5 min readConcept 13 of 43

What it is

Custom properties (commonly called CSS variables) allow you to define a specific value once—like a brand color or a standard padding size—and reuse it everywhere in your CSS.

They always begin with two dashes (like --brand-color) and are accessed using the var() function.

Why it matters

Without variables, updating a design is a nightmare. If your brand color changes, you have to use 'Find and Replace' across hundreds of files, hoping you don't accidentally replace the wrong thing.

With custom properties, you update the value in exactly one place (usually the :root selector), and every button, link, and border in your entire application updates instantly.

How it works

You define a custom property inside a selector to set its scope. Usually, we put global variables in :root so the entire HTML document can access them.

css :root { --primary: #3b82f6; --spacing-lg: 2rem; }

Then, you apply them using the var() function:

css .button { background-color: var(--primary); padding: var(--spacing-lg); }

Try it

Change the --brand and --radius variables and watch the entire component system update instantly.

The Power of One Source of Truth

Update --brand-color

Update --radius

8px
0px32px
/* 1. Define variables at the root */
:root {
--brand-color: #3b82f6;
--radius: 8px;
}
 
/* 2. Use them everywhere */
.btn {
background-color: var(--brand-color);
border-radius: var(--radius);
}

Component System

.btn
.input:focus
Focus state gets the brand color...
.badge
New Feature
Notice how the badge computes half the radius: `calc(var(--radius) / 2)`
By injecting variables at the root container, all child components inherit the values. Changing the variables updates everything in the subtree instantly without compiling any CSS!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1How do you apply a custom property named '--highlight' to a background color?
  2. 2Which prefix is mandatory when defining a CSS custom property?
  3. 3What is a major advantage of native CSS variables over Sass/LESS variables?

Remember this

  • Define custom properties with a -- prefix.
  • Use them by wrapping the name in the var() function.
  • Place global variables in the :root selector.
  • Variables are live in the DOM and inherit down the element tree.

Done with this concept?

Mark it complete to track your progress. No login needed.