Tailwind CSS v4 Migration: CSS-First Config and Design Tokens
Derar SattoufUpdated Next.js & frontend

Tailwind CSS v4 is not a version bump you can ignore. The configuration moved from a JavaScript file into your stylesheet, the engine was rewritten, a handful of utilities were renamed or removed, and the default theme now uses modern CSS features such as oklch() colors and native cascade layers. The good news is that the change is mostly mechanical, there is an official upgrade tool, and the result is a smaller, faster and more transparent toolchain: your design tokens become real CSS custom properties that you can read in DevTools, override at runtime and share with non-Tailwind code.
As of late 2026 the v4 line is mature: v4.0 shipped in January 2025 and has had many minor releases since (the 4.1, 4.2 and 4.3 lines added features such as text shadows, masks, a webpack plugin and more). Exact patch numbers change often, so I describe behavior rather than patch versions and mark details that may have moved with "verify against current docs." The canonical references are the Tailwind CSS docs and the v4 upgrade guide.
Tailwind v4 is CSS-first: replace @tailwind base; @tailwind components; @tailwind utilities; with a single @import "tailwindcss"; and move theme config into an @theme block in CSS. Everything in @theme becomes a CSS variable (for example --color-brand-500) and a utility (bg-brand-500). Namespaces decide which utilities exist: --color-*, --font-*, --text-*, --breakpoint-*, --radius-*, --shadow-*, --spacing and more.
Run the official tool in a clean git branch: npx @tailwindcss/upgrade. It updates dependencies, config and many class names. Review the diff; don't trust it blindly. Then install the right integration: @tailwindcss/postcss for PostCSS and Next.js, @tailwindcss/vite for Vite, @tailwindcss/cli for the CLI. You no longer need postcss-import or autoprefixer. The browser baseline is modern evergreen (Safari 16.4+, Chrome 111+, Firefox 128+ at the v4.0 release), so if you must support older browsers, stay on v3.4. Verify against the current docs.
A few renames to know: shadow-sm became shadow-xs, shadow became shadow-sm, rounded-sm became rounded-xs, outline-none became outline-hidden, bg-gradient-to-r became bg-linear-to-r, flex-shrink-0 became shrink-0. Opacity utilities such as bg-opacity-50 are gone; use bg-black/50. Defaults changed too: border color is currentColor, ring is 1px, buttons use cursor: default, and hover: only applies on devices that support hover. Dark mode is prefers-color-scheme by default; for a class or data attribute toggle, declare it with @custom-variant dark.
Build tokens in three layers: primitive (raw scale), semantic (purpose, such as --color-surface), and component (optional). Components consume semantic tokens only, so theme switching means changing variable values, not rewriting classes. Use @theme inline when a theme token points at another variable, and @theme static when you need a variable emitted even if no utility uses it. Keep cva + clsx + tailwind-merge (use a version that supports v4) behind a single cn() helper; shadcn/ui supports v4 and uses @theme inline. Check contrast in the token file, not in components: text needs 4.5:1, large text and UI boundaries 3:1.
Decision table: should you migrate now?
| Situation | Recommendation | Why |
|---|---|---|
| New project | Start on v4 | No migration cost, best defaults, current docs and ecosystem |
| v3 app, evergreen browsers only | Migrate | Faster builds, CSS-native tokens, simpler config |
| v3 app that must support old Safari or older browsers | Stay on v3.4 until your support policy changes | v4 relies on @property, color-mix() and cascade layers |
Heavy JS plugin ecosystem (custom addUtilities plugins) | Migrate in a branch, convert plugins gradually | @plugin still loads JS plugins, but verify each plugin supports v4 |
| Sass, Less or Stylus preprocessing around Tailwind | Remove the preprocessor from the Tailwind path first | v4 is not designed to be used with preprocessors |
| Large design system with many apps | Migrate the shared preset or token package first | One CSS token file can be imported by every app |
| Time-boxed release this week | Do not migrate | Migration is safe but needs visual review time |
What changed in v4, in one page
The engine
v4 ships a new engine, often called Oxide, written largely in Rust, with parsing and transformation handled in part by Lightning CSS. In practice this means three things. Builds are substantially faster (Tailwind's announcement reported full builds several times faster and incremental builds with no new CSS orders of magnitude faster; measure your own project instead of quoting numbers). Vendor prefixing and minification are built in, so autoprefixer is no longer needed. And imports are resolved by Tailwind itself, so postcss-import is no longer needed either.
CSS-first configuration
In v3 you had tailwind.config.js with a theme.extend object. In v4 you write configuration in CSS:
@import "tailwindcss";
@theme {
--font-display: "Satoshi", "Inter", sans-serif;
--breakpoint-3xl: 120rem;
--color-brand-500: oklch(0.62 0.19 259);
--ease-snappy: cubic-bezier(0.2, 0, 0, 1);
}Each variable in a theme namespace creates matching utilities and is exposed on :root as a CSS variable. Add --color-brand-500 and you immediately get bg-brand-500, text-brand-500, border-brand-500, ring-brand-500, fill-brand-500 and so on. Add --breakpoint-3xl and you get a 3xl: variant. This is the central idea: the theme is data in CSS, and utilities are generated from it.
Automatic content detection
You no longer list content globs. Tailwind scans your project, respects .gitignore, and skips binary files. When something outside the detected set needs scanning (a package in node_modules, a shared UI library in a monorepo), register it with @source:
@import "tailwindcss";
@source "../node_modules/@acme/ui/dist";
@source not "../src/legacy";Newer v4 releases also let you force-generate classes that never appear literally in your source with @source inline("..."), which replaces most uses of the old safelist. Verify the exact syntax in the current docs for your minor version.
Modern CSS under the hood
v4 uses cascade layers (@layer theme, base, components, utilities), registered custom properties with @property, and color-mix() for opacity modifiers. The default palette moved to oklch(), which is perceptually more uniform and can express wider-gamut P3 colors. This is also why the browser baseline moved up.
New features worth knowing
| Feature | Example | Notes |
|---|---|---|
| Container queries (built in) | @container on parent, @sm:flex, @max-md:hidden on child | No plugin needed |
| Dynamic spacing and grid values | w-17, mt-13, grid-cols-15 | Spacing derives from a single --spacing variable |
| 3D transforms | rotate-x-12, perspective-distant, transform-3d | Check browser support for your audience |
| Gradient improvements | bg-linear-45, bg-radial, bg-conic, interpolation modifiers like /oklch | Renamed from bg-gradient-* |
@starting-style support | starting:opacity-0 | Enter animations without JavaScript |
not-* variant | not-hover:opacity-75, not-first:mt-4 | Wraps :not() |
| Group-like variants | in-focus:, nth-3:, has-checked: | in-* works like an implicit group |
inset-shadow-*, inset-ring-* | inset-ring-1 inset-ring-black/10 | Stackable shadow layers |
field-sizing-content | on a textarea | Auto-growing inputs without JS |
color-scheme-* | color-scheme-dark | Sets native control theming |
@utility | custom utilities with variant support | Replaces plugin addUtilities |
@custom-variant | your own variants such as theme-midnight: | Replaces addVariant |
@plugin | load legacy JS plugins | Still supported |
Releases after 4.0 added more, including text shadows, mask utilities, user-valid and user-invalid variants, and @source inline. Always check the changelog for the minor you run.
What was removed
- The
@tailwinddirectives (use@import "tailwindcss"). - Deprecated opacity utilities:
bg-opacity-*,text-opacity-*,border-opacity-*,divide-opacity-*,ring-opacity-*,placeholder-opacity-*. Use the slash modifier:bg-black/50. corePlugins,safelistandseparatoroptions in the JS config.- Preprocessor support (Sass, Less, Stylus) as a first-class path.
- Several renamed utilities (covered in the migration section).
- The
theme()function in CSS is deprecated in favor ofvar(--color-...).
Setup: PostCSS, Vite, Next.js and the CLI
Pick the integration that matches your bundler. All of them need the same CSS entry file.
The CSS entry file
/* src/app/globals.css */
@import "tailwindcss";That single line pulls in the theme, base (preflight) and utilities layers.
Next.js (App Router)
Next.js uses PostCSS, so install the PostCSS plugin:
npm install tailwindcss @tailwindcss/postcss postcss// postcss.config.mjs
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;Import the stylesheet in your root layout:
// src/app/layout.tsx
import "./globals.css";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<body>{children}</body>
</html>
);
}For the caching and data patterns of the rest of an App Router app, see Next.js Server Components, Caching and Data Patterns.
Vite
npm install tailwindcss @tailwindcss/vite// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [react(), tailwindcss()],
});The Vite plugin is the recommended path for Vite projects because it integrates with the module graph and is faster than running PostCSS.
Tailwind CLI
npm install tailwindcss @tailwindcss/cli
npx @tailwindcss/cli -i ./src/input.css -o ./dist/output.css --watchOther bundlers
Newer v4 releases added a webpack loader/plugin; check the installation docs for the current list of framework guides. If you use CSS Modules, Vue style blocks or Svelte style blocks, each file is processed separately and does not see your theme. Add @reference "../app/globals.css"; at the top of such a file so @apply and theme variables resolve, or better, use plain utility classes in markup and avoid @apply in isolated stylesheets.
Editor and tooling
Install the official Tailwind CSS IntelliSense extension and make sure it points at your CSS entry file. For monorepos with several entry files, check the extension's setting for the stylesheet location (verify the current setting name in the extension docs).
Step-by-step migration lab
This lab assumes a v3.x app with tailwind.config.js, PostCSS and some custom plugins. Budget half a day for a mid-size app, mostly for visual review.
Step 0: Create a safety net
git switch -c chore/tailwind-v4
git status # must be clean
npm run build # confirm the v3 baseline builds
npm run testCapture visual baselines of your key pages. If you use Playwright, take screenshots now so you can diff after the upgrade. If you do not have visual tests, collect before/after screenshots manually for the ten most important screens.
Step 1: Upgrade to the latest v3 first
Fix deprecation warnings while still on v3. Make sure Node 20 or newer is installed; the upgrade tool requires it.
Step 2: Run the official upgrade tool
npx @tailwindcss/upgradeThe tool updates your dependencies, converts the JavaScript config into CSS where it can, replaces @tailwind directives with @import "tailwindcss", and rewrites many renamed utilities in your templates. It handles the common cases well and leaves the unusual ones for you.
Step 3: Read the diff, file type by file type
git diff --stat
git diff -- '*.css'
git diff -- 'package.json' 'postcss.config.*' 'vite.config.*'
git diff -- '*.tsx' | head -300Look for these in order: dependencies, PostCSS or Vite config, CSS entry, config conversion, class renames.
Step 4: Fix the config conversion
A typical v3 config:
// tailwind.config.js (v3)
module.exports = {
content: ["./src/**/*.{ts,tsx}"],
darkMode: "class",
theme: {
extend: {
colors: {
brand: { 500: "#4f46e5", 600: "#4338ca" },
},
fontFamily: { sans: ["Inter", "sans-serif"] },
screens: { "3xl": "1920px" },
},
},
plugins: [require("@tailwindcss/typography")],
};becomes:
/* globals.css (v4) */
@import "tailwindcss";
@plugin "@tailwindcss/typography";
@custom-variant dark (&:where(.dark, .dark *));
@theme {
--color-brand-500: #4f46e5;
--color-brand-600: #4338ca;
--font-sans: "Inter", sans-serif;
--breakpoint-3xl: 120rem;
}If the tool could not convert something, you can keep a JS config temporarily with @config "../../tailwind.config.js"; as a bridge, but treat that as migration debt and remove it.
Step 5: Search for known renames the tool might miss
Dynamic class names built by string concatenation are invisible to codemods. Search for them:
rg "shadow-sm|shadow\b|rounded-sm|rounded\b|outline-none|ring\b|blur-sm|drop-shadow-sm" src --glob '*.{ts,tsx,html,mdx}'
rg "bg-opacity|text-opacity|border-opacity|flex-shrink|flex-grow|overflow-ellipsis|decoration-slice|bg-gradient-to" srcStep 6: Verify, then review visually
npm run build
npm run lint
npm run test
npx playwright test --update-snapshots=noneWalk the key screens in light and dark mode, at mobile and desktop widths, and with keyboard focus. Focus rings, borders, shadows and button cursors are where v4 defaults visibly differ.
Step 7: Remove migration scaffolding
Delete tailwind.config.js if no longer needed, remove autoprefixer and postcss-import from package.json, and remove any @config bridge. Commit in small, reviewable commits: dependencies, config, class renames, then fixes.
Step 8: Ship behind your normal release process
Deploy to a preview environment, compare against production, and only then merge. Keep the branch revertable; the migration is a single squash commit that can be reverted cleanly.
The breaking changes and renames, as a table
| v3 | v4 | Notes |
|---|---|---|
@tailwind base; @tailwind components; @tailwind utilities; | @import "tailwindcss"; | One import |
shadow-sm | shadow-xs | Scale shifted down one step |
shadow | shadow-sm | Same |
drop-shadow-sm / drop-shadow | drop-shadow-xs / drop-shadow-sm | Same shift |
blur-sm / blur | blur-xs / blur-sm | Same shift |
backdrop-blur-sm / backdrop-blur | backdrop-blur-xs / backdrop-blur-sm | Same shift |
rounded-sm / rounded | rounded-xs / rounded-sm | Same shift |
outline-none | outline-hidden | outline-none now truly sets outline-style: none, which removes the forced-colors fallback |
ring (3px) | ring-3 | Default ring width is now 1px |
ring default color blue-500 | currentColor | Specify a ring color explicitly |
border default gray-200 | currentColor | Add an explicit border-gray-200 or restore in base layer |
bg-opacity-50 | bg-black/50 | Slash modifier |
flex-shrink-0 / flex-grow | shrink-0 / grow | Old names removed |
overflow-ellipsis | text-ellipsis | Rename |
decoration-slice / decoration-clone | box-decoration-slice / box-decoration-clone | Rename |
bg-gradient-to-r | bg-linear-to-r | Gradients got linear, radial, conic families |
bg-[--brand] | bg-(--brand) | Variable shorthand uses parentheses |
flex! (important at end) | !flex (important at start) | Old position deprecated but accepted |
first:*:pt-0 (right-to-left stacking) | *:first:pt-0 (left-to-right) | Variant stacking order reversed |
space-x-4, space-y-4 selector | now targets :not(:last-child) margin-bottom/inline-end | Behavior in edge cases differs; prefer gap |
container config (center, padding) | define with @utility container | Config options removed |
theme(colors.red.500) in CSS | var(--color-red-500) | theme() deprecated |
tailwindcss-animate | tw-animate-css | For shadcn/ui users |
prefix: "tw-" | @import "tailwindcss" prefix(tw); and classes like tw:flex | Prefix is now a variant-style prefix |
Behavioral changes without renames:
- Buttons use
cursor: default(as the browser does) rather thanpointer. If your design wants pointer cursors, add a base rule (shown in the full theme later). - Placeholder text now uses the current text color at 50% mix, not gray-400.
hover:applies only when the primary input supports hover (@media (hover: hover)), so it no longer sticks on touch devices after a tap.- Transforms use the individual CSS properties
translate,rotate,scale;transform-noneno longer resets them. Usetranslate-none,rotate-noneorscale-none. hiddenattribute is respected overdisplayutilities in preflight.- Default
line-heighton text sizes, the default color of<dialog>backdrops and similar preflight details may change subtly. Visual review is the only reliable check.
Dark mode and custom variants
Media-based (default)
With no configuration, dark: follows prefers-color-scheme. That is the right default for sites without a toggle.
Class or attribute based
@import "tailwindcss";
/* class strategy: toggle the "dark" class on html */
@custom-variant dark (&:where(.dark, .dark *));/* data attribute strategy: set data-theme="dark" on html */
@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));:where() keeps specificity at zero, which makes dark variants easy to override.
Avoiding the flash of the wrong theme
Set the theme before first paint with a tiny inline script in the document head. In Next.js, next-themes does this for you, or you can add the script yourself:
// src/app/layout.tsx (head script excerpt)
const themeScript = `
try {
const stored = localStorage.getItem("theme");
const dark = stored ? stored === "dark" : window.matchMedia("(prefers-color-scheme: dark)").matches;
document.documentElement.classList.toggle("dark", dark);
document.documentElement.style.colorScheme = dark ? "dark" : "light";
} catch (_) {}
`;
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<script dangerouslySetInnerHTML={{ __html: themeScript }} />
</head>
<body>{children}</body>
</html>
);
}Custom variants beyond dark
@custom-variant is how you add variants for themes, states or app-specific attributes:
@custom-variant theme-midnight (&:where([data-theme="midnight"], [data-theme="midnight"] *));
@custom-variant aria-current-page (&[aria-current="page"]);
@custom-variant pointer-coarse-only (@media (pointer: coarse));Use them sparingly. The best theming does not need a variant per theme: it changes variable values (see the design tokens section below) so that the same classes work everywhere.
Custom utilities, variants and plugins
@utility
Define a utility that participates in variants (hover:, md:, dark:) automatically:
@utility text-balance-tight {
text-wrap: balance;
letter-spacing: -0.01em;
}
@utility scrollbar-thin {
scrollbar-width: thin;
scrollbar-color: var(--color-border-strong) transparent;
}Functional utilities take a value from a theme namespace:
@theme {
--tab-size-2: 2;
--tab-size-4: 4;
--tab-size-github: 8;
}
@utility tab-* {
tab-size: --value(--tab-size-*);
}The --value() function resolves from theme keys, bare numbers, or arbitrary values. Check the functions and directives reference for the exact forms supported by your version.
@variant inside your own CSS
When writing custom CSS you can apply a variant to a rule:
.card {
background: var(--color-surface);
@variant dark {
background: var(--color-surface-raised);
}
@variant hover {
box-shadow: var(--shadow-md);
}
}@plugin and legacy JS
@plugin "@tailwindcss/typography";
@plugin "@tailwindcss/forms";
@plugin "./plugins/my-plugin.js";First-party plugins keep working. Third-party plugins vary: some were updated for v4, some rely on v3 internals. Test each one, and replace simple ones with @utility.
@apply and when to use it
@apply still works and is useful for styling third-party HTML you cannot add classes to (rendered markdown, CMS output) and for base styles. Prefer components in your framework over @apply-based CSS classes; @apply in many places makes it harder to see what styles an element has.
Design tokens that scale
A design token is a named design decision: --color-surface, --radius-control, --space-section. The mistake most teams make is naming tokens after their value (--blue-500 everywhere in components) rather than their purpose. That makes theming and rebranding expensive.
The three-layer model
Layer 1: PRIMITIVES raw scales, no meaning
--color-indigo-500, --color-slate-900, --spacing, --radius-lg
Layer 2: SEMANTIC purpose, themable, what components use
--color-surface, --color-text, --color-primary, --color-danger,
--color-border, --color-ring
Layer 3: COMPONENT optional, for design systems with many variants
--button-bg, --button-fg, --card-paddingRules:
- Primitives are defined once and almost never change.
- Semantic tokens point at primitives and are the only layer that changes per theme (light, dark, brand A, brand B, high contrast).
- Components use semantic tokens only. A button never says
bg-indigo-600; it saysbg-primary. - Component tokens are optional. Add them only where a component needs internal knobs.
Mapping to @theme
In Tailwind v4, tokens live in @theme. There are three flavors:
| Directive | Behavior | Use it for |
|---|---|---|
@theme { ... } | Generates utilities and emits a CSS variable only if the variable is used by some utility or CSS (tree-shaken variables) | Primitives and one-off tokens |
@theme inline { ... } | Generates utilities that inline the value, not the variable reference | Tokens whose value is var(--something-else), such as semantic tokens that swap per theme |
@theme static { ... } | Always emits the variable, even if unused | Tokens read by JavaScript or external CSS |
The inline option matters for theming. Suppose you write:
:root { --primary: oklch(0.55 0.2 260); }
.dark { --primary: oklch(0.7 0.15 260); }
@theme {
--color-primary: var(--primary);
}Tailwind generates .bg-primary { background-color: var(--color-primary); } and --color-primary is declared on :root as var(--primary). Because custom properties resolve where they are declared in inheritance, a .dark scope that changes --primary can fail to flow into elements that use --color-primary defined on :root (the var() was resolved at :root, not at the element). Using @theme inline emits background-color: var(--primary) directly in the utility, so it resolves at the element and respects the scope. This is the reason shadcn/ui uses @theme inline.
Color tokens in OKLCH
OKLCH describes a color as lightness, chroma and hue: oklch(0.62 0.19 259). It is practical for design systems because holding lightness constant gives predictable contrast across hues, and generating a scale means changing lightness in steps. Tailwind v4's default palette is OKLCH. You can still use hex or hsl() values; the opacity modifier (bg-primary/50) works with any because it uses color-mix().
Non-color tokens
Treat all of these as tokens, not just color:
| Token type | Namespace | Example |
|---|---|---|
| Radius | --radius-* | --radius-control: 0.5rem gives rounded-control |
| Shadow | --shadow-* | --shadow-card: 0 1px 2px oklch(0 0 0 / 0.08) |
| Font family | --font-* | --font-display gives font-display |
| Font size | --text-* | --text-body: 1rem with --text-body--line-height: 1.6 |
| Breakpoint | --breakpoint-* | --breakpoint-3xl: 120rem |
| Container size | --container-* | --container-prose: 65ch gives max-w-prose and the container query variant @prose: |
| Easing | --ease-* | --ease-snappy gives ease-snappy |
| Animation | --animate-* | --animate-fade-in: fade-in 200ms var(--ease-snappy) |
| Spacing base | --spacing | --spacing: 0.25rem drives p-4, w-17 |
To remove the whole default palette and force your team to use only your tokens, reset the namespace:
@theme {
--color-*: initial;
--color-surface: oklch(1 0 0);
--color-text: oklch(0.2 0.02 260);
}Resetting is strong medicine: it deletes bg-red-500. It is the right call for a strict design system, and the wrong call for a prototype.
Animations and keyframes as tokens
Define keyframes inside @theme so they are emitted with the animation token:
@theme {
--animate-fade-in: fade-in 200ms var(--ease-snappy) both;
@keyframes fade-in {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
}
}Respect reduced motion by pairing with the motion-safe: and motion-reduce: variants: motion-safe:animate-fade-in.
Light and dark themes with semantic variables
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
:root {
--background: oklch(0.99 0.003 260);
--foreground: oklch(0.2 0.02 260);
--card: oklch(1 0 0);
--muted: oklch(0.96 0.005 260);
--muted-foreground: oklch(0.45 0.02 260);
--primary: oklch(0.52 0.2 262);
--primary-foreground: oklch(0.99 0 0);
--border: oklch(0.9 0.01 260);
--ring: oklch(0.52 0.2 262);
--danger: oklch(0.55 0.22 27);
}
.dark {
--background: oklch(0.16 0.015 260);
--foreground: oklch(0.96 0.005 260);
--card: oklch(0.2 0.015 260);
--muted: oklch(0.25 0.015 260);
--muted-foreground: oklch(0.72 0.02 260);
--primary: oklch(0.72 0.15 262);
--primary-foreground: oklch(0.16 0.015 260);
--border: oklch(0.3 0.015 260);
--ring: oklch(0.72 0.15 262);
--danger: oklch(0.7 0.18 25);
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-border: var(--border);
--color-ring: var(--ring);
--color-danger: var(--danger);
}Components then write bg-background text-foreground border-border, with no dark: prefixes at all for themed values. Dark mode becomes a variable swap, which cuts the class count in your markup and removes a whole class of "forgot the dark variant" bugs.
When you still need dark:
Use explicit dark: for one-off differences that are not part of the token system: an image that needs dark:invert, a shadow that should disappear in dark mode, an illustration swap. If you find yourself writing the same dark: pair repeatedly, promote it to a semantic token.
Multi-brand and multi-theme
The same mechanism handles brands. Scope variables to a data attribute:
[data-brand="acme"] {
--primary: oklch(0.55 0.22 25);
--primary-foreground: oklch(0.99 0 0);
--radius-control: 0.25rem;
}
[data-brand="globex"] {
--primary: oklch(0.5 0.15 165);
--primary-foreground: oklch(0.99 0 0);
--radius-control: 1rem;
}
[data-brand="globex"].dark,
.dark [data-brand="globex"] {
--primary: oklch(0.75 0.14 165);
--primary-foreground: oklch(0.15 0.02 165);
}// Apply the brand per tenant at the layout or subtree level
export function TenantShell({ brand, children }: { brand: "acme" | "globex"; children: React.ReactNode }) {
return <div data-brand={brand}>{children}</div>;
}Because brand is a subtree attribute, you can preview two brands side by side on one page, which is useful for design review and visual tests. Keep brand-specific overrides to semantic tokens only; if a brand needs a different layout, that is a component variant, not a token.
Sharing tokens across apps
Put the token CSS in a package and import it:
/* packages/ui/styles/tokens.css */
@theme inline { /* ... semantic tokens ... */ }
:root { /* ... */ }
.dark { /* ... */ }/* apps/web/src/app/globals.css */
@import "tailwindcss";
@import "@acme/ui/styles/tokens.css";
@source "../../../../packages/ui/src";The @source line is what makes Tailwind scan the shared package's components. Forgetting it is the number one cause of "classes from my UI package have no styles" in monorepos.
Exporting tokens to other platforms
Because tokens are CSS variables, JavaScript can read them at runtime with getComputedStyle(document.documentElement).getPropertyValue("--primary"). For canvas or chart libraries that need color strings, read the variable rather than duplicating hex values. For native apps or Figma, pair this approach with a token pipeline such as the W3C Design Tokens Community Group format and a build tool like Style Dictionary (verify current versions); keep one source of truth and generate the others.
Naming conventions that age well
| Do | Do not |
|---|---|
--color-surface, --color-surface-raised | --color-white, --color-light-gray |
--color-primary, --color-primary-foreground | --color-blue, --color-btn-blue |
--color-danger, --color-warning, --color-success | --color-red-text, --color-error-red-dark |
--radius-control, --radius-card | --radius-8 in components |
--text-body, --text-heading-lg | --text-16 |
Pair every background token with a foreground token that is guaranteed to pass contrast on it (primary with primary-foreground). Components then pick the pair and never choose a text color on their own.
Component patterns: cn, cva, clsx, tailwind-merge, shadcn/ui
The cn() helper
// src/lib/cn.ts
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}clsx resolves conditionals and arrays into a string. twMerge removes conflicting Tailwind classes so that the last one wins: cn("p-2", "p-4") returns p-4. Use a tailwind-merge release that supports Tailwind v4 (the v3 line of the library targets v4; verify in its docs).
Variants with cva
class-variance-authority turns a component's visual API into typed data:
// src/components/ui/button.tsx
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/cn";
const buttonVariants = cva(
[
"inline-flex items-center justify-center gap-2 rounded-control font-medium",
"transition-colors cursor-pointer",
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",
"disabled:pointer-events-none disabled:opacity-50",
],
{
variants: {
variant: {
primary: "bg-primary text-primary-foreground hover:bg-primary/90",
secondary: "bg-muted text-foreground hover:bg-muted/80",
outline: "border border-border bg-background hover:bg-muted",
danger: "bg-danger text-white hover:bg-danger/90",
ghost: "hover:bg-muted",
},
size: {
sm: "h-9 px-3 text-sm",
md: "h-10 px-4 text-sm",
lg: "h-12 px-6 text-base",
icon: "size-10",
},
},
defaultVariants: { variant: "primary", size: "md" },
},
);
export type ButtonProps = React.ComponentProps<"button"> & VariantProps<typeof buttonVariants>;
export function Button({ className, variant, size, ...props }: ButtonProps) {
return <button className={cn(buttonVariants({ variant, size }), className)} {...props} />;
}Notes for React 19: ref is a normal prop on function components, so there is no forwardRef wrapper here. Notice that every color is a semantic token, so this component needs zero changes for dark mode or a new brand.
Compound variants and states
const badgeVariants = cva("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium", {
variants: {
tone: {
neutral: "bg-muted text-muted-foreground",
success: "bg-success/15 text-success",
danger: "bg-danger/15 text-danger",
},
interactive: { true: "cursor-pointer hover:opacity-80", false: "" },
},
compoundVariants: [{ tone: "danger", interactive: true, className: "hover:bg-danger/25" }],
defaultVariants: { tone: "neutral", interactive: false },
});Data attributes over conditional classes
For stateful primitives (Radix, Base UI, native details, dialog), style via attributes rather than JS-driven class toggles:
<button
aria-expanded={open}
className="data-[state=open]:bg-muted aria-expanded:bg-muted"
>
Menu
</button>v4 supports aria-* and data-* variants out of the box, and bare data attributes work too (data-active:bg-muted matches the presence of the attribute).
shadcn/ui with Tailwind v4
shadcn/ui provides copy-in components, not a package. Its current setup targets Tailwind v4: tokens are OKLCH, the theme is wired with @theme inline, components carry data-slot attributes, and tw-animate-css replaces tailwindcss-animate. To start:
npx shadcn@latest init
npx shadcn@latest add button dialog dropdown-menuTo upgrade an existing shadcn project, follow the shadcn Tailwind v4 guide and keep these points in mind. You own the component code, so after the Tailwind upgrade tool runs, re-read each component for renamed utilities (outline-none, shadow-sm, rounded-sm). Re-run the add command for components you have not customized to pick up upstream fixes. Keep customizations in tokens rather than in component files where possible so future upgrades are a clean diff.
Class ordering and long class strings
Long class lists are fine when each element is a small component. If a single element has more than about fifteen classes, you are likely missing a component, a variant or a token. Extract a component rather than reaching for @apply.
Performance
Build time
The new engine is fast enough that Tailwind is rarely the bottleneck. If your dev server feels slow after migration, check these first: the @source globs (a broad path such as the repository root pulls in build output), huge generated directories not covered by .gitignore, and the PostCSS pipeline (extra plugins such as legacy postcss-nested are redundant because Tailwind handles nesting).
CSS size
Utilities are generated on demand, so size depends on which classes you use, not on how large the framework is. Track the compiled CSS size in CI:
npm run build
ls -l .next/static/css/*.css | awk '{ print $5, $9 }'
gzip -c .next/static/css/*.css | wc -cTypical sources of bloat: dynamic class names that force @source inline ranges, @theme blocks that define hundreds of unused variables with static, and safelisting entire palettes.
Runtime cost of theming
CSS variable swapping is cheap, but changing a variable on :root invalidates style for the whole document. For theme toggles this is fine. For per-frame animations, animate transform and opacity on the element, not a root variable.
Avoid dynamic class names
Tailwind detects classes by scanning source as plain text, so this does not work:
// BAD: the full class name never appears in source
const bad = `bg-${color}-500`;
// GOOD: complete class names appear literally
const colorClass = {
red: "bg-red-500",
green: "bg-green-500",
} as const;This rule is unchanged from v3 and remains the top cause of "my class does nothing in production."
Fonts and layout shift
Tokens for fonts (--font-sans) should point at fonts loaded with font-display: swap or optional and, in Next.js, at the CSS variable produced by next/font:
import { Inter } from "next/font/google";
const inter = Inter({ subsets: ["latin"], variable: "--font-inter", display: "swap" });
// <html className={inter.variable}>@theme inline {
--font-sans: var(--font-inter), ui-sans-serif, system-ui, sans-serif;
}Use inline here too, since the value references another variable defined on html.
Accessibility of color and focus in your tokens
Tokens are the best place to enforce accessibility because a single number controls hundreds of components.
Contrast requirements
| What | WCAG criterion | Minimum |
|---|---|---|
| Normal text | 1.4.3 Contrast (Minimum), AA | 4.5:1 |
| Large text (18pt, or 14pt bold) | 1.4.3, AA | 3:1 |
| UI component boundaries and focus indicators, meaningful graphics | 1.4.11 Non-text Contrast, AA | 3:1 against adjacent colors |
| Enhanced text contrast | 1.4.6, AAA | 7:1 |
A contrast test for your token file
Check every foreground and background pair in both themes, as part of CI. A minimal script using the culori library (verify its API in the docs):
// scripts/check-contrast.ts
import { parse, wcagContrast } from "culori";
type Pair = { name: string; fg: string; bg: string; min: number };
const light: Pair[] = [
{ name: "text on background", fg: "oklch(0.2 0.02 260)", bg: "oklch(0.99 0.003 260)", min: 4.5 },
{ name: "muted text on background", fg: "oklch(0.45 0.02 260)", bg: "oklch(0.99 0.003 260)", min: 4.5 },
{ name: "primary-foreground on primary", fg: "oklch(0.99 0 0)", bg: "oklch(0.52 0.2 262)", min: 4.5 },
{ name: "border on background (UI)", fg: "oklch(0.7 0.01 260)", bg: "oklch(0.99 0.003 260)", min: 3 },
];
let failed = 0;
for (const p of light) {
const ratio = wcagContrast(parse(p.fg)!, parse(p.bg)!);
const ok = ratio >= p.min;
console.log(`${ok ? "PASS" : "FAIL"} ${p.name}: ${ratio.toFixed(2)} (min ${p.min})`);
if (!ok) failed++;
}
process.exit(failed ? 1 : 0);Parsing the CSS file to extract pairs automatically is better than a hand-kept list; the point is that contrast is a test, not an opinion.
Focus styles as a token
Make the focus ring a token and apply it globally so no component forgets it:
@layer base {
:where(a, button, input, select, textarea, summary, [tabindex]):focus-visible {
outline: 2px solid var(--color-ring);
outline-offset: 2px;
}
}WCAG 2.2 adds 2.4.11 Focus Not Obscured (Minimum) at AA, so also make sure sticky headers do not cover the focused element; scroll-padding-top on html helps. Do not use outline-none unless you add a replacement; use outline-hidden only when you provide a visible alternative, because outline-hidden still shows an outline in forced-colors mode.
Motion and forced colors
Tailwind ships motion-safe:, motion-reduce: and forced-colors: variants. Use motion-reduce:transition-none motion-reduce:animate-none on decorative animation. Use the forced-colors: variant to restore borders that your design draws with background color alone.
Linting, formatting and editor setup
Prettier plugin
prettier-plugin-tailwindcss sorts classes into the canonical order. With v4 you tell it where your stylesheet is so it can read your theme:
{
"plugins": ["prettier-plugin-tailwindcss"],
"tailwindStylesheet": "./src/app/globals.css",
"tailwindFunctions": ["cn", "cva", "clsx"]
}tailwindFunctions makes the plugin sort strings inside those function calls, which covers cva variant strings. Keep the plugin last in the plugin list if you use others. Verify option names against the plugin README.
ESLint
eslint-plugin-tailwindcss has historically lagged major Tailwind releases; check its current support for v4 before depending on it, and consider rules that do not need Tailwind knowledge (for example banning arbitrary hex values with a custom no-restricted-syntax rule to enforce tokens). Biome offers a class sorting rule (useSortedClasses) if you use Biome instead of Prettier (verify current status; it was marked nursery for some time).
Enforcing tokens
A simple CI grep keeps raw colors out of components:
# fail if a component uses raw palette colors instead of semantic tokens
if rg -n "(bg|text|border|ring|fill|stroke)-(red|blue|green|slate|gray|zinc|indigo)-[0-9]{2,3}" src/components; then
echo "Use semantic tokens (bg-primary, text-foreground, ...) in components"
exit 1
fiAllow exceptions in a clearly named folder (for example marketing illustrations).
Editor setup
Enable class sorting on save, and enable the IntelliSense extension for cn(, cva( and clsx( function calls through its classFunctions setting (verify the setting name in the extension documentation).
Common migration breakages and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| No styles at all | Missing @import "tailwindcss", or CSS file not imported, or the PostCSS plugin still named tailwindcss | Use @tailwindcss/postcss; import the CSS in the root layout or entry |
Build error: "It looks like you're trying to use tailwindcss directly as a PostCSS plugin" | Old plugin config | Replace with @tailwindcss/postcss |
| Classes from a UI package are unstyled | Package outside auto-detected sources | Add @source "../path/to/package" |
| Borders suddenly black or text-colored | Default border color is now currentColor | Add explicit border-border, or restore globally in base layer |
| Focus rings look thinner, a different color | ring is 1px and currentColor | Use ring-3 ring-ring where you want the old look |
outline-none inputs lose focus visibility in Windows high contrast mode | Semantics changed | Use outline-hidden plus a visible focus style |
| Buttons no longer show a pointer cursor | v4 preflight default | Add button:not(:disabled) { cursor: pointer; } in base layer |
@apply fails: "Cannot apply unknown utility class" in a CSS module or Vue block | The file does not know your theme | Add @reference "../path/to/globals.css"; |
| Custom utility with a variant does not work | Defined in plain CSS rather than @utility | Re-define with @utility |
Arbitrary variable syntax broken: bg-[--brand] | Syntax changed | Use bg-(--brand) |
| Gradient classes do nothing | bg-gradient-to-r renamed | Use bg-linear-to-r |
| Dark mode stopped following the toggle | v4 defaults to media queries | Add @custom-variant dark |
| Dark variables do not apply to semantic colors | Used @theme instead of @theme inline for var() references | Switch to @theme inline |
A theme variable is missing from :root | Tree-shaken because unused | Use @theme static, or reference it |
| Container is no longer centered with padding | container config options removed | Use @utility container { margin-inline: auto; padding-inline: 1rem; } |
| Plugin throws or produces nothing | Plugin relies on v3 internals | Update the plugin, replace with @utility, or drop it |
| Prettier no longer sorts classes correctly | Plugin cannot find the theme | Set tailwindStylesheet |
Different spacing in space-y-* children | Selector change | Prefer flex flex-col gap-* |
Transform reset (transform-none) leaves rotation | Individual transform properties | Use rotate-none, scale-none, translate-none |
@import of a CSS file placed after other rules ignored | @import must be first | Move imports to the top |
| Safari older than 16.4 breaks | Unsupported baseline | Stay on v3 or raise support policy |
Debugging playbook
- Run the build and read the first error only; later errors are usually fallout.
- Inspect the element in DevTools. If the class is present but no rule applies, the utility was not generated: check content detection and dynamic class names.
- If the rule exists but is overridden, look at layers. Unlayered custom CSS beats utilities in the cascade, because utilities live in
@layer utilities. Put custom component CSS inside@layer components, or accept that unlayered CSS wins. - If a variable is undefined, check whether it is tree-shaken and whether it is declared in the scope the element sees.
- Reproduce in the Tailwind Play environment at play.tailwindcss.com when you suspect a bug in Tailwind itself.
When NOT to use these patterns
- Do not migrate mid-sprint on a critical path. The mechanical part is quick; the visual review is the cost.
- Do not reset the default palette on a small project.
--color-*: initialis for design systems with an enforced palette. For a portfolio, extend instead. - Do not build three token layers for a five-page site. Primitives plus semantic tokens are enough. Add component tokens only when a component needs variants that share knobs.
- Do not use
@applyto recreate Bootstrap. If you find yourself writing.btn,.cardand.form-inputclasses, write components. - Do not theme with a
dark:class on every element when semantic tokens can do it in one place. - Do not put runtime-computed colors in
@theme. Tokens are compile-time. For user-chosen colors (for example a tenant brand color stored in a database), set a CSS variable at runtime withstyleon a wrapper and reference it from a semantic token. - Do not use Tailwind for email HTML without a tool that inlines CSS and downlevels modern color functions; email clients do not support
oklch()or layers. - Do not rely on v4 for browsers outside the baseline. Check your analytics before migrating.
A complete theme file
This file combines the pieces above into a production-shaped globals.css for a Next.js app: semantic tokens, light and dark themes, brand overrides, fonts, radius and shadows, animations, base styles, and a custom container.
@import "tailwindcss";
@plugin "@tailwindcss/typography";
/* Class-based dark mode */
@custom-variant dark (&:where(.dark, .dark *));
/* Scan the shared UI package in the monorepo */
@source "../../../../packages/ui/src";
/* ---------- Layer 1 + 2: values that change per theme ---------- */
:root {
--background: oklch(0.99 0.003 260);
--foreground: oklch(0.2 0.02 260);
--card: oklch(1 0 0);
--card-foreground: oklch(0.2 0.02 260);
--muted: oklch(0.96 0.005 260);
--muted-foreground: oklch(0.45 0.02 260);
--primary: oklch(0.52 0.2 262);
--primary-foreground: oklch(0.99 0 0);
--success: oklch(0.5 0.14 150);
--warning: oklch(0.6 0.15 75);
--danger: oklch(0.55 0.22 27);
--border: oklch(0.9 0.01 260);
--input: oklch(0.85 0.01 260);
--ring: oklch(0.52 0.2 262);
--radius: 0.625rem;
}
.dark {
--background: oklch(0.16 0.015 260);
--foreground: oklch(0.96 0.005 260);
--card: oklch(0.2 0.015 260);
--card-foreground: oklch(0.96 0.005 260);
--muted: oklch(0.25 0.015 260);
--muted-foreground: oklch(0.72 0.02 260);
--primary: oklch(0.72 0.15 262);
--primary-foreground: oklch(0.16 0.015 260);
--success: oklch(0.72 0.15 150);
--warning: oklch(0.8 0.14 80);
--danger: oklch(0.7 0.18 25);
--border: oklch(0.3 0.015 260);
--input: oklch(0.35 0.015 260);
--ring: oklch(0.72 0.15 262);
}
/* Optional brand override (subtree attribute) */
[data-brand="globex"] {
--primary: oklch(0.5 0.15 165);
--ring: oklch(0.5 0.15 165);
}
/* ---------- Tokens that reference variables: use inline ---------- */
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-success: var(--success);
--color-warning: var(--warning);
--color-danger: var(--danger);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-control: calc(var(--radius) - 2px);
--font-sans: var(--font-inter), ui-sans-serif, system-ui, sans-serif;
--font-mono: var(--font-jetbrains), ui-monospace, monospace;
}
/* ---------- Static tokens (no variable references) ---------- */
@theme {
--breakpoint-3xl: 120rem;
--shadow-card: 0 1px 2px oklch(0 0 0 / 0.06), 0 4px 12px oklch(0 0 0 / 0.04);
--ease-snappy: cubic-bezier(0.2, 0, 0, 1);
--animate-fade-in: fade-in 200ms var(--ease-snappy) both;
@keyframes fade-in {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
}
}
/* ---------- Base styles ---------- */
@layer base {
html {
color-scheme: light;
scroll-padding-top: 5rem; /* keeps focused items visible below sticky headers */
}
html.dark { color-scheme: dark; }
body {
background-color: var(--color-background);
color: var(--color-foreground);
font-family: var(--font-sans);
}
* { border-color: var(--color-border); }
button:not(:disabled), [role="button"]:not([aria-disabled="true"]) { cursor: pointer; }
:where(a, button, input, select, textarea, summary, [tabindex]):focus-visible {
outline: 2px solid var(--color-ring);
outline-offset: 2px;
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
}
/* ---------- Custom utilities ---------- */
@utility container {
margin-inline: auto;
padding-inline: 1rem;
@media (width >= 40rem) { padding-inline: 1.5rem; }
@media (width >= 64rem) { padding-inline: 2rem; }
}
@utility text-balance-tight {
text-wrap: balance;
letter-spacing: -0.01em;
}Usage in a component:
export function Card({ title, children }: { title: string; children: React.ReactNode }) {
return (
<section className="rounded-lg border border-border bg-card p-6 text-card-foreground shadow-card motion-safe:animate-fade-in">
<h2 className="text-balance-tight text-xl font-semibold">{title}</h2>
<div className="mt-3 text-muted-foreground">{children}</div>
</section>
);
}Nothing in that component mentions dark mode, a brand or a hex value, and all three work.
Rollout checklist for a team
Use this as a pull request template for the migration.
- Branch created, baseline build and tests green on v3
- Browser support policy confirmed against the v4 baseline
-
npx @tailwindcss/upgraderun; dependencies updated - PostCSS or Vite plugin switched;
autoprefixerandpostcss-importremoved - CSS entry uses
@import "tailwindcss"; config converted to@theme - Dark mode strategy declared with
@custom-variant darkif class or attribute based -
@sourceadded for monorepo packages and external UI libraries - Renamed utilities fixed, including dynamically built class strings
- Border, ring, outline and cursor defaults reviewed
-
tailwind-merge,cva,clsxversions compatible;cn()tested - shadcn/ui components re-read for renamed utilities;
tw-animate-cssin place - Prettier plugin has
tailwindStylesheet; CI formatting check passes - Contrast test runs on both themes
- Visual regression run on key pages, light and dark, mobile and desktop
- CSS bundle size compared against v3
- Preview deployment reviewed by a designer
- Legacy config, bridges and dead plugins removed
If you only change one thing
Move your colors into semantic variables with @theme inline, delete the dark: pairs you no longer need, and add a contrast test. That makes your next rebrand, your dark mode and your accessibility audit all cheaper, and it's the best use of the new CSS-first model.
Questions that come up
Is tailwind.config.js completely gone?
It is no longer needed. You can still load one with @config for gradual migrations, and @plugin loads JS plugins. New work should use CSS.
How do I support runtime theming from a database value?
Set a CSS variable via an inline style on a wrapper and point a semantic token at it. Tokens in @theme are static at build time.
Does v4 work with CSS Modules?
Yes, but each module is compiled in isolation. Use @reference to give @apply access to your theme, or prefer utility classes in markup.
How do I keep the old default border color?
Add * { border-color: var(--color-gray-200); } in @layer base, or better, use a semantic border token as shown in the theme file.
Can I mix v3 and v4 in a monorepo? Yes, per app, since each app compiles its own CSS. Do not share one Tailwind config or token package between v3 and v4 apps without separate entry points.
Is OKLCH required?
No. Hex, rgb() and hsl() all work, including opacity modifiers. OKLCH is recommended for scales and wide-gamut colors.
Sources and docs
- Tailwind CSS documentation
- Upgrade guide (v3 to v4)
- Theme variables (
@theme) - Functions and directives
- Dark mode
- Detecting classes in source files
- Tailwind CSS v4.0 announcement
- Tailwind CSS blog and GitHub releases, for what's new since you last read this; verify details (new utilities,
@sourceforms, plugin lists) against the version you install - shadcn/ui with Tailwind v4
- prettier-plugin-tailwindcss
- class-variance-authority
- tailwind-merge
- OKLCH color picker and explainer
- WCAG 2.2 Quick Reference