CSS Variables
CSS Custom Properties (variables) are the backbone of modern theming. Tailwind v4 embraces them natively, making your designs infinitely customizable.
What Are CSS Variables?
CSS Custom Properties (commonly called CSS Variables) let you define reusable values that can be referenced anywhere in your stylesheet. They're declared with a -- prefix and accessed with var().
Vanilla CSS Variables
:root {
--brand-color: #6366f1;
--radius: 0.5rem;
--spacing-unit: 1rem;
}
.card {
background: var(--brand-color);
border-radius: var(--radius);
padding: var(--spacing-unit);
}
/* Change the variable — every usage updates! */
.theme-ocean {
--brand-color: #0ea5e9;
}Tailwind v4's @theme
Tailwind v4 introduced a native @theme directive. Instead of configuring colors in a JavaScript config file, you define your design tokens directly in CSS — and they become CSS variables automatically.
Defining Custom Tokens in globals.css
/* globals.css */
@import "tailwindcss";
@theme {
--color-brand: #6366f1;
--color-brand-light: #818cf8;
--color-brand-dark: #4338ca;
--color-surface: #ffffff;
--color-surface-dark: #0a0a0a;
--radius-card: 1rem;
--spacing-section: 4rem;
}
/* Now you can use them as Tailwind utilities! */
/* bg-brand, text-brand-light, rounded-card, etc. */ The Magic: Once you define
--color-brand inside @theme, Tailwind automatically generates utilities like bg-brand, text-brand, border-brand, etc. No config file needed!Using Arbitrary Values
Even without @theme, you can reference any CSS variable directly in Tailwind using the square bracket syntax. This is great for consuming variables from third-party libraries or existing design systems.
Arbitrary Value Syntax
/* Reference any CSS variable inline: */ <div className="bg-[var(--brand-color)]"> Uses a custom variable </div> <div className="text-[var(--heading-color)]"> Dynamic heading color </div> <div className="p-[var(--spacing-unit)]"> Dynamic padding </div> /* You can even do calculations: */ <div className="w-[calc(var(--sidebar-width)+2rem)]"> Computed width </div>
Quick Reference
| Method | When to Use |
|---|---|
| @theme { --color-x } | Your own design tokens — generates full utility classes |
| bg-[var(--x)] | One-off references to external/third-party variables |
| :root { --x } | Vanilla CSS approach — works but no auto-generated utilities |