CSS Variables (Custom Properties)

Reusable, dynamic, and powerful: Master CSS custom properties with hands-on examples!

What Are CSS Variables?

CSS variables (also called custom properties) allow you to store values in reusable variables directly in your CSS. They make your stylesheets more maintainable, flexible, and dynamic.
Syntax: --variable-name: value; and usage: var(--variable-name).

Example 1: Global Variables

:root {
  --main-bg: #f0f4ff;
  --accent: #3498db;
  --radius: 12px;
}
.box {
  background: var(--main-bg);
  border: 2px solid var(--accent);
  border-radius: var(--radius);
  color: var(--accent);
  padding: 1rem 2rem;
  font-weight: bold;
}
This box uses global CSS variables!

How CSS Variables Work

Example 2: Local Scope & Overriding

/* A default theme variable */
:root {
  --theme-bg: #f0f0f0;
  --theme-text: #333;
}
.theme-light {
  --theme-bg: #fff;
  --theme-text: #222;
}
.theme-dark {
  --theme-bg: #222;
  --theme-text: #fff;
}
.card {
  background: var(--theme-bg);
  color: var(--theme-text);
  padding: 1rem 2rem;
  border-radius: 8px;
  margin-bottom: 1rem;
}
Default Theme
Light Theme Card
Dark Theme Card

Best Practices & Tips

Example 3: Fallback Values

.fallback-demo {
  /* --not-set is not defined */
  color: var(--not-set, #e74c3c);
  font-size: 1.2rem;
  padding: 0.5rem 1rem;
  border: 1px dashed var(--not-set, #e74c3c);
  border-radius: 6px;
}
This uses a fallback color because --not-set is not defined.

Further Reading