Sub topic 3
Defining design tokens with @theme
This chapter assumes you know basic CSS, including custom properties and var(). It also assumes you have used Tailwind utility classes and know how to import Tailwind into a CSS file with @import "tailwindcss".
What @theme does
In Tailwind v4, you configure your design system in CSS. The @theme directive is where you declare design tokens. A design token is a named value, such as a brand color or a font, that your project reuses.
Each variable you put in @theme does two things:
- It becomes a normal CSS variable in the generated stylesheet.
- It tells Tailwind to create matching utility classes and variants.
A plain :root variable only does the first. That difference is the reason @theme exists.
A first theme
@import "tailwindcss";
@theme {
--font-display: "Satoshi", "sans-serif";
--breakpoint-3xl: 120rem;
--color-avocado-100: oklch(0.99 0 0);
--color-avocado-500: oklch(0.84 0.18 117.33);
--ease-fluid: cubic-bezier(0.3, 0, 0, 1);
}Now you can use the new tokens in markup:
<div class="bg-avocado-500 font-display 3xl:grid-cols-6 grid grid-cols-2">
<p class="text-avocado-100">Themed content</p>
</div>These classes only work because the variables exist. bg-avocado-500, font-display and text-avocado-100 are utilities. 3xl: is a variant that applies at the 120rem breakpoint.
How a name picks its utilities
The prefix of each variable name is its namespace. Tailwind reads the namespace to decide what to generate.
| Variable | Namespace | Generates |
|---|---|---|
| `--font-display` | `--font-*` | `font-display` |
| `--breakpoint-3xl` | `--breakpoint-*` | `3xl:*` variants |
| `--color-avocado-500` | `--color-*` | `bg-avocado-500`, `text-avocado-500`, and other color utilities |
| `--ease-fluid` | `--ease-*` | `ease-fluid` |
The part after the namespace becomes the name in the class. So --color-avocado-500 gives avocado-500.
Common errors
- Wrong namespace. Writing
--brand-color: #3f3cbbgenerates nobg-brand-colorutility. Use--color-brandinstead. - Putting tokens in
:rootand expecting utilities. Variables in:rootare ordinary CSS variables. Tailwind does not read them to build classes. - Declaring
@themeinside a selector or media query.@thememust be at the top level of your CSS.
Exercise
You add --color-brand: #3f3cbb; to @theme. Which utility can you now use for a background, and why does --brand-color fail to give you one?
Show answer
You can use bg-brand. The --color- prefix is the namespace that tells Tailwind to generate color utilities. --brand-color does not start with a known namespace, so it is only a CSS variable and creates no utility.
Exercise
Which variable creates a 4xl: variant: --breakpoint-4xl: 140rem; or --screen-4xl: 140rem;?
Show answer
--breakpoint-4xl: 140rem;. The --breakpoint-* namespace generates responsive variants.