Using CSS Variables in Tailwind
Define design tokens as CSS custom properties and reference them inside the Tailwind config to create dynamic, theme-aware values.
CSS Custom Properties as Design Tokens
CSS custom properties (also called CSS variables) let you define values once and reference them throughout your stylesheet. They are runtime values — they can be changed by JavaScript or by switching a class on a parent element. Combining CSS variables with Tailwind's config creates a powerful theming system: design tokens live in CSS variables, and Tailwind generates utility classes that reference those variables.
/* CSS variables defined in :root */
:root {
--color-primary: #6366f1;
--color-surface: #ffffff;
--color-on-surface: #111827;
--spacing-section: 5rem;
}
/* Dark mode swaps values without changing class names */
.dark {
--color-surface: #1f2937;
--color-on-surface: #f9fafb;
}Referencing CSS Variables in Tailwind Config
Wire CSS variables into Tailwind's config using the var(--variable-name) syntax as the value. This creates utility classes that output var() references in the generated CSS. At runtime, when the variable value changes (such as in dark mode or on theme switch), all elements using those utility classes update instantly without rebuilding the CSS or toggling additional classes.
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
primary: 'var(--color-primary)',
surface: 'var(--color-surface)',
'on-surface': 'var(--color-on-surface)',
},
spacing: {
section: 'var(--spacing-section)',
},
},
},
};All lessons in this course
- Adding Custom Colors
- Custom Font Families
- Custom Spacing Values
- Using CSS Variables in Tailwind