0PricingLogin
Tailwind CSS Academy · Lesson

CSS Variable-Based Theming

Store design tokens as CSS custom properties and reference them in Tailwind's config to enable runtime theme switching without recompilation.

Why CSS Variables for Theming?

CSS custom properties (CSS variables) are the key to runtime theming with Tailwind. Unlike static values baked into the compiled CSS, CSS variables can be changed by JavaScript at any time without reloading the page. This makes them ideal for implementing light/dark mode switches, user-selectable themes, or multi-tenant branding where the same application needs to look different for different clients.

Defining CSS Variables in :root

CSS variables are defined on the :root selector so they are globally available throughout the page. The syntax is --variable-name: value. You reference them with var(--variable-name). Place these definitions in your global CSS file — typically globals.css or index.css — so they are present before any component styles are applied.

/* globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  :root {
    --color-primary: #3b82f6;
    --color-primary-hover: #1d4ed8;
    --color-surface: #ffffff;
    --color-surface-alt: #f8fafc;
    --color-text: #111827;
    --color-text-muted: #6b7280;
    --color-border: #e5e7eb;
  }
}

All lessons in this course

  1. Primitive vs Semantic Tokens
  2. CSS Variable-Based Theming
  3. Multi-Brand Theming Strategy
  4. Token Documentation and Governance
← Back to Tailwind CSS Academy