CSS Variables (Custom Properties)

CSS Variables, also called custom properties, let you store values (like colors, spacing, fonts) in reusable variables. They’re defined with a --name syntax and used with var(--name).

1) Defining & Using Variables


:root{
  --primary-color: #1E88E5;
  --secondary-color: #43A047;
}
.btn{
  background: var(--primary-color);
  color: #fff;
}
Primary Box
Secondary Box

2) Fallback Values


.alert{
  color: var(--danger, red); /* uses red if --danger not defined */
}

If a variable isn’t defined, var() can provide a fallback.

3) Scope & Inheritance


:root { --text-color: black; }
.dark  { --text-color: white; }
p      { color: var(--text-color); }

Dark theme variable override.

4) Theming with Variables


.theme-light{
  --bg: #fff;
  --fg: #111;
}
.theme-dark{
  --bg: #111;
  --fg: #fff;
}
.panel{
  background: var(--bg);
  color: var(--fg);
}
Light Panel
Dark Panel

Notes:

  • Variables are live: if changed with JS (document.documentElement.style.setProperty), the style updates instantly.
  • They cascade: children inherit from parents unless overridden.
  • Unlike SASS/LESS variables, CSS variables work at runtime, not compile time.
  • Use :root to define global variables for easy theming.