🍋
Menu
How-To Beginner 1 min read 204 words

CSS Custom Properties (Variables): A Complete Guide

Master CSS custom properties — from basic variable usage to advanced patterns like theming, component APIs, and responsive design tokens. Understand how they differ from preprocessor variables and when to use each.

Key Takeaways

  • CSS custom properties (declared with `--`) are fundamentally different from Sass/Less variables.
  • background: var(--color-primary);
  • Define theme tokens as custom properties and swap them for different themes:
  • Custom properties create clean component interfaces.
  • Custom properties trigger style recalculation when changed.

Custom Properties vs Preprocessor Variables

CSS custom properties (declared with --) are fundamentally different from Sass/Less variables. Custom properties exist at runtime — they cascade, inherit, and can be changed dynamically with JavaScript. Preprocessor variables are compile-time constants that disappear in the output CSS.

Basic Usage

:root {
  --color-primary: #3b82f6;
  --spacing-md: 1rem;
  --radius-lg: 0.75rem;
}

.button {
  background: var(--color-primary);
  padding: var(--spacing-md);
  border-radius: var(--radius-lg);
}

Theming with Custom Properties

Define theme tokens as custom properties and swap them for different themes:

:root { --bg: #ffffff; --text: #1a1a1a; }
.dark { --bg: #1a1a1a; --text: #ffffff; }

Every element using var(--bg) automatically updates when the .dark class is toggled — no JavaScript per-element manipulation needed.

Component APIs

Custom properties create clean component interfaces. The component defines defaults, and consumers override only what they need:

.card {
  padding: var(--card-padding, 1.5rem);
  background: var(--card-bg, white);
}

Performance Considerations

Custom properties trigger style recalculation when changed. Avoid changing properties on :root during animations — scope them to the animated element to limit the recalculation scope. For static design tokens, preprocessor variables perform slightly better since they compile away.

Generate and preview CSS custom property themes with the Peasy CSS tools.