stackademic

The leading education platform for anyone with an interest in software development.

CSS Custom Properties

Define reusable theme variables with CSS custom properties

Overview

Custom properties (CSS variables) store values you can reuse and override. They cascade and inherit—define design tokens on :root and override per component or theme (e.g. dark mode).

Syntax / Usage

:root {
  --color-primary: #2563eb;
  --color-text: #1f2937;
  --space-md: 1rem;
  --radius: 0.5rem;
  --font-sans: system-ui, sans-serif;
}

.button {
  background: var(--color-primary);
  padding: var(--space-md);
  border-radius: var(--radius);
  font-family: var(--font-sans);
}

/* Fallback value */
color: var(--color-muted, #6b7280);

/* Dark theme override */
[data-theme="dark"] {
  --color-text: #f9fafb;
  --color-primary: #60a5fa;
}

Examples

Component-scoped tokens:

.alert {
  --alert-bg: #fef3c7;
  --alert-border: #f59e0b;
  background: var(--alert-bg);
  border: 1px solid var(--alert-border);
}

.alert-error {
  --alert-bg: #fee2e2;
  --alert-border: #ef4444;
}

Animate with variables:

.progress {
  --value: 0;
  width: calc(var(--value) * 1%);
  transition: width 0.3s ease;
}

Common Mistakes

  • Expecting variables to work in media query conditions—they do not (yet)
  • Defining variables only on components without :root tokens
  • Typos in var(--name) failing silently to fallback or invalid
  • Over-nesting overrides making theme switching hard to trace

See Also

selectors responsive-design box-model flexbox