Module 8 · Mastery · Lesson 1 of 5

CSS Custom Properties

Advanced ⏱ 20 min2 sections · 1 exercise · 4-question quiz

Custom properties turn CSS into a system: define a value once on :root, reference it everywhere with var(), redefine it per theme or per component. They're the mechanism behind this site's entire dark mode.

1. Define, use, fallback

CSS — the pattern
:root {
  --brand: #5A8AB9;
  --radius: 14px;
  --space: 1rem;
}
.card {
  background: var(--surface, #fff);   /* fallback if unset */
  border-radius: var(--radius);
  padding: calc(var(--space) * 1.5);  /* math with variables */
}

Declared on :root they're global; declared anywhere else they scope to that subtree. Unlike preprocessor variables they live at runtime — JavaScript can read and write them, and calc() composes them freely.

2. Theming: the killer app

CSS — dark mode in one block
:root {
  --paper: #F5F7F8;
  --ink:   #20242A;
}
[data-theme="dark"] {
  --paper: #141A21;
  --ink:   #E8EDF2;
}
body { background: var(--paper); color: var(--ink); }

Flip one attribute and every var() consumer updates — no duplicate stylesheets. Press the moon icon in this site's header: you're watching exactly this technique. The same scoping powers component variants: set --accent differently per card class and shared rules render differently.

3. Try it yourself

Extract the repeated blue into --brand on :root and use var(--brand) in both rules — then change the variable once to #E0594A and watch both update.

exercise.html — editable

4. Quiz — check your understanding

CSS Custom Properties Quiz

4 questions · pass at 60%

Q1. Custom properties are declared and read with…

Double-dash to declare, var() to consume.

Q2. Where do you declare a globally available variable?

:root is the html element — the top of the cascade, visible everywhere.

Q3. var(--gap, 16px) — the 16px is…

The second argument is the fallback value.

Q4. Why are custom properties ideal for theming?

One scoped redefinition cascades to everything that uses var() — instant theme.
🏆
Quiz passed? You're one step closer to your certificate.

Every lesson quiz you pass (60%+) is saved in your browser and counts toward the CSSmatic Certificate of Completion.

Track my progress →