Next.jsEasy
How do you use Tailwind CSS in Next.js?
create-next-app sets up Tailwind CSS v4 by default. Manually, install tailwindcss and @tailwindcss/postcss, add the plugin to postcss.config.mjs, put @import "tailwindcss"; in app/globals.css, and import that file in the root layout. Tailwind works in Server and Client Components with no runtime cost.
Tailwind v4 setup
npm install tailwindcss @tailwindcss/postcss postcsspostcss.config.mjs:export default { plugins: { "@tailwindcss/postcss": {} } }app/globals.css:@import "tailwindcss";app/layout.tsx:import "./globals.css";
No tailwind.config.js and no content paths are needed: v4 detects source files automatically.
Customization in CSS
@theme { --color-brand: #4f46e5; --font-sans: var(--font-geist-sans); }createsbg-brand,font-sansand similar utilities.@custom-variant dark (&:where(.dark, .dark *));for class-based dark mode.@plugin "@tailwindcss/typography";to load plugins.@source "../packages/ui";to scan extra folders, such as monorepo packages.
Tailwind v3
Still supported (the docs keep a v3 guide): tailwind.config.js with content globs and @tailwind base; @tailwind components; @tailwind utilities;.
Tips
- Use
clsxandtailwind-merge(often combined as acn()helper) for conditional classes. - Combine with
next/fontby exposing the font as a CSS variable. - Production CSS includes only the classes you use.
- Do not build class names dynamically from strings (
bg-${color}-500); Tailwind cannot detect them.
Code example
tsx
1// postcss.config.mjs2// export default { plugins: { "@tailwindcss/postcss": {} } };34/* app/globals.css */5// @import "tailwindcss";6// @theme {7// --color-brand: oklch(0.55 0.2 270);8// --font-sans: var(--font-geist-sans);9// }10// @custom-variant dark (&:where(.dark, .dark *));1112// app/page.tsx13import { cn } from "@/lib/cn"; // clsx + tailwind-merge1415export default function Home({ active = true }: { active?: boolean }) {16 return (17 <main className="mx-auto max-w-3xl p-6">18 <h1 className="text-3xl font-bold text-slate-900 dark:text-white">Hello</h1>19 <button20 className={cn(21 "rounded-lg px-4 py-2 font-medium transition",22 active ? "bg-brand text-white hover:opacity-90" : "bg-slate-200 text-slate-600"23 )}24 >25 Get started26 </button>27 </main>28 );29}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.