Semantic Color Tokens with CSS Custom Properties

Create a semantic color token system that maps abstract roles (background, text, primary, error) to specific palette values using CSS variables.

Semantic Colors

Detailed Explanation

Semantic Color Tokens

Semantic tokens add an abstraction layer between your color palette and your components. Instead of referencing --blue-500 directly, components use --color-primary, which resolves to a palette value. This indirection is the foundation of scalable theming.

Two-Layer Architecture

/* Layer 1: Palette (primitive tokens) */
:root {
  --blue-500: #3b82f6;
  --blue-600: #2563eb;
  --gray-50:  #fafafa;
  --gray-900: #18181b;
  --red-500:  #ef4444;
  --green-500: #22c55e;
}

/* Layer 2: Semantic tokens */
:root {
  --color-bg:       var(--gray-50);
  --color-text:     var(--gray-900);
  --color-primary:  var(--blue-500);
  --color-primary-hover: var(--blue-600);
  --color-error:    var(--red-500);
  --color-success:  var(--green-500);
}

Benefits

  1. Theme switching — Override only semantic tokens, not every component.
  2. Design consistency — Developers pick from roles, not arbitrary hex values.
  3. Refactoring safety — Change a palette color once, all semantic references update.
  4. Documentation — Token names communicate intent (--color-error vs --red-500).

Naming Conventions

Pattern Example When to use
Role-based --color-primary General-purpose themes
Component-scoped --button-bg Component libraries
Interactive state --color-primary-hover Systems with hover/focus states

Anti-Patterns

  • Too many tokens: If you have 200 semantic tokens, the abstraction has become a burden. Aim for 15-30 core tokens.
  • Leaking primitives: If components reference --blue-500 directly alongside semantic tokens, the layer is broken.
  • Missing fallbacks: Always provide a fallback: var(--color-primary, #3b82f6) for safety during migrations.

Use Case

Design system teams building a token architecture that separates raw palette colors from the semantic roles used in component styles, enabling multi-theme support and design consistency.

Try It — CSS Variable Generator

Open full tool