Using CSS Variables for Color Tokens in Tailwind
Learn how to combine CSS custom properties with Tailwind for powerful, themeable color systems.
css-variablesthemingdesign-tokensadvanced
advanced12 min readtutorial
Why CSS Variables with Tailwind?
CSS variables (custom properties) enable runtime theme switching, reduce configuration complexity, and allow colors to be changed without rebuilding CSS.
Setting Up CSS Variables
/* styles/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--color-primary: 59 130 246; /* RGB values without rgb() */
--color-secondary: 139 92 246;
--color-accent: 236 72 153;
--color-background: 255 255 255;
--color-foreground: 15 23 42;
--color-success: 34 197 94;
--color-warning: 245 158 11;
--color-error: 239 68 68;
}
.dark {
--color-primary: 96 165 250;
--color-secondary: 167 139 250;
--color-accent: 244 114 182;
--color-background: 15 23 42;
--color-foreground: 241 245 249;
}
}Tailwind Configuration
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
primary: 'rgb(var(--color-primary) / <alpha-value>)',
secondary: 'rgb(var(--color-secondary) / <alpha-value>)',
accent: 'rgb(var(--color-accent) / <alpha-value>)',
background: 'rgb(var(--color-background) / <alpha-value>)',
foreground: 'rgb(var(--color-foreground) / <alpha-value>)',
success: 'rgb(var(--color-success) / <alpha-value>)',
warning: 'rgb(var(--color-warning) / <alpha-value>)',
error: 'rgb(var(--color-error) / <alpha-value>)',
}
}
}
}Usage in Components
<div class="bg-background text-foreground">
<button class="bg-primary text-white hover:bg-primary/90">
Primary Button
</button>
<button class="bg-secondary/10 text-secondary">
Secondary Button
</button>
<span class="text-success">Success message</span>
</div>JavaScript Theme Switching
// Switch to a custom theme at runtime
function setTheme(theme) {
const root = document.documentElement;
root.style.setProperty('--color-primary', theme.primary);
root.style.setProperty('--color-secondary', theme.secondary);
// ... set other colors
}Frequently Asked Questions
Why use RGB values without rgb()?
Storing just the numbers (e.g., '59 130 246') allows Tailwind's opacity modifier to work. The <alpha-value> placeholder gets replaced with the opacity.
Can I use HSL instead of RGB?
Yes, but you'd need to change the format to hsl(var(--color) / <alpha-value>) and store values like '217 91% 60%'.
Try Our Color Tools
50+ free tools for Tailwind CSS developers. No signup required.
Explore Tools