Course contentsShow
← Web Development
Lesson 648 of 2,98211. Utility-First CSS with TailwindFree lesson

CSS Custom Properties with Tailwind

Combine Tailwind utilities with CSS custom properties to create dynamic, runtime-switchable themes.

CSS Custom Properties with Tailwind

What you'll learn: How to combine Tailwind's utility classes with CSS custom properties (variables) to create themes you can change dynamically at runtime without rebuilding your CSS.

Why Mix Custom Properties with Tailwind?

Tailwind is powerful for design consistency, but it compiles at build time. CSS custom properties let you change values in the browser without recompiling. Together, they give you the best of both worlds: Tailwind's utility system with runtime flexibility.

Think of it like building with LEGO blocks (Tailwind utilities) where you can swap out the colors of the blocks on the fly (custom properties) without rebuilding the entire structure.

How It Works

Define CSS custom properties in your Tailwind config, then reference them in utility classes. You can update these properties with JavaScript or through CSS classes to switch themes instantly.

In your tailwind.config.js:

module.exports = {
  theme: {
    extend: {
      colors: {
        primary: 'var(--color-primary)',
        secondary: 'var(--color-secondary)',
      }
    }
  }
}

In your CSS:

:root {
  --color-primary: #3b82f6;
  --color-secondary: #8b5cf6;
}

[data-theme="dark"] {
  --color-primary: #60a5fa;
  --color-secondary: #a78bfa;
}

In your HTML:

<button class="bg-primary text-white">Click Me</button>

Now changing data-theme="dark" on a parent element updates all bg-primary elements instantly—no rebuild required.

Common Use Cases

  • Light/dark theme switching
  • Brand color customization per user
  • A/B testing different color schemes
  • Multi-tenant applications with different branding

Key Takeaway: CSS custom properties bridge Tailwind's build-time utilities with runtime flexibility, enabling dynamic theming without sacrificing Tailwind's utility-first approach.