CSS Custom Properties for Color Systems in Tailwind

Build flexible, runtime-adjustable color systems using CSS custom properties integrated with Tailwind CSS.

css-variablescustom-propertiesruntimedynamic
intermediate10 min readtutorial

CSS Custom Properties and Tailwind

CSS custom properties (also called CSS variables) let you define reusable values that can change at runtime. Tailwind can reference these variables, giving you the best of both worlds: utility-first workflow with dynamic color control.

Setting Up Color Variables

/* globals.css */
@layer base {
  :root {
    --clr-bg: #ffffff;
    --clr-text: #0f172a;
    --clr-primary: #3b82f6;
    --clr-primary-hover: #2563eb;
    --clr-border: #e2e8f0;
  }
}

/* tailwind.config.js */
module.exports = {
  theme: {
    extend: {
      colors: {
        bg: 'var(--clr-bg)',
        text: 'var(--clr-text)',
        primary: 'var(--clr-primary)',
        'primary-hover': 'var(--clr-primary-hover)',
        border: 'var(--clr-border)',
      }
    }
  }
};

Runtime Color Updates

// Change colors at runtime without rebuilding CSS
document.documentElement.style.setProperty('--clr-primary', '#8b5cf6');
document.documentElement.style.setProperty('--clr-primary-hover', '#7c3aed');

// All elements using bg-primary instantly update
// <button class="bg-primary hover:bg-primary-hover text-white">

Scoped Color Overrides

CSS custom properties inherit through the DOM. You can override colors for specific sections of the page without adding extra classes.

<!-- Hero section with custom primary -->  
<section style="--clr-primary: #ec4899; --clr-primary-hover: #db2777;">
  <button class="bg-primary hover:bg-primary-hover text-white px-6 py-3 rounded-lg">
    Pink button in this section only
  </button>
</section>

Frequently Asked Questions

Can I use opacity modifiers with CSS variable colors?

Yes, if you store raw channel values. For example, store '59 130 246' and reference as rgb(var(--clr-primary) / <alpha-value>) in your Tailwind config.

Do CSS variables work with Tailwind's JIT mode?

Yes. Tailwind JIT generates utility classes that reference your CSS variables. The actual color values resolve at runtime in the browser.

Try Our Color Tools

50+ free tools for Tailwind CSS developers. No signup required.

Explore Tools