CSS3
CSS3

CSS Variables (Custom Properties)

A CSS variable, formally called a custom property, lets you store a value once and reuse it everywhere change it in one place, and every element using it updates automatically. Define one on :root (a selector meaning 'the whole document', typically the <html> tag), using a double-dash prefix: :root { --brand-color: #1E2A5A; --spacing: 16px; }. Then use it anywhere with the var() function: color: var(--brand-color); or padding: var(--spacing);. The real power shows up in large projects: instead of hunting through hundreds of lines to change a brand color used in fifty different places, you update the single --brand-color declaration once, and every var(--brand-color) reference across the entire site instantly reflects the new value. Variables can even be overridden inside a specific section redeclaring --brand-color inside a .dark-theme class, for instance, lets that section use a different value while the rest of the page keeps the original.

Why this matters

  • ·Changing one variable instantly updates every element that references it, site-wide
  • ·Variables make theming (like dark mode) far easier to implement and maintain
  • ·They give meaningful names (--brand-color) to values instead of repeating raw hex codes everywhere

Common mistakes

  • ·Forgetting the double-dash (--) prefix means the variable declaration is invalid and silently ignored
  • ·Using var() with a variable that was never defined falls back to nothing (or a specified fallback) instead of erroring loudly
  • ·Overriding variables in too many nested scopes can make it hard to trace which value actually applies
Your code
Live preview

Frequently asked questions

A double dash, like --brand-color. Without it, the browser doesn't recognize it as a custom property.

Practice questions

Question 1

Define a --spacing variable on :root and use it for a box's padding.

Your code
Live preview

Question 2

Define a --brand-color variable and use it for both text color and border color on the same element.

Your code
Live preview

Quick check

Just for this topic answer honestly, then check yourself.

1 / 10

What prefix marks a CSS custom property?