Tailwind CSS with Next.js
Tailwind CSS with Next.js is a common pairing because both tools share the same goal: fast, predictable results with less custom code. Tailwind is a utility-first CSS framework. Instead of writing separate stylesheets, you apply small classes like flex, p-4, or text-center directly in your JSX. The App Router and Tailwind work together without special configuration in new projects.
This tutorial shows you how to add Tailwind to a new project with create-next-app and to an existing one. You will learn the current setup for Tailwind v4, which uses a single import in globals.css. You will also see how to use responsive prefixes, hover and focus states, dark mode, and how to keep your components readable when class lists grow long.
If you are still setting up your project structure, the tutorial on Next.js Setup & Project Structure will help you understand where files live. For styling images inside your components, see Next.js Image Optimization.
What Is Tailwind CSS and How Does It Work with Next.js?
Tailwind CSS is a utility-first CSS framework that provides low-level classes for spacing, colors, typography, and layout. You build designs by combining these classes in your HTML or JSX. With Next.js, Tailwind works in both Server and Client Components because it is purely CSS resolved at build time .
// app/page.tsx
export default function HomePage() {
return (
<h1 className="text-3xl font-bold text-blue-600">
Hello, Next.js with Tailwind
</h1>
);
}
Browser shows: A large, bold, blue heading. You did not write a separate CSS file or create a class name. The classes text-3xl, font-bold, and text-blue-600 each set one CSS property.
How it works: The className prop in JSX is the standard way to add classes to an element. Tailwind scans your project files for class names and generates only the CSS you use. This keeps the final stylesheet small. Because Tailwind is CSS-only, it does not care whether the component runs on the server or the client .
Installing Tailwind CSS in a New or Existing Project
If you start with create-next-app, the setup is automatic. If you have an existing Next.js project, you need a few manual steps. The instructions below describe Tailwind CSS v4, which is the version current scaffolding installs .
New project with create-next-app
# Terminal
npx create-next-app@latest my-app --typescript --tailwind --app --src-dir
Output: The project is created with Tailwind already configured. A globals.css file contains the import, and a postcss.config.mjs file is set up. You can start using utility classes immediately.
Adding Tailwind to an existing project
# Terminal
npm install tailwindcss @tailwindcss/postcss postcss
// postcss.config.mjs
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
/* app/globals.css */
@import "tailwindcss";
Output: After restarting the dev server, utility classes work in your components. No tailwind.config.js file is required for basic use in v4 .
How it works: Tailwind v4 uses a CSS-first approach. The @import "tailwindcss" line replaces the three @tailwind directives from v3. The PostCSS plugin processes your CSS and generates the utilities you use. If you see old tutorials referencing tailwind.config.js, content arrays, or @tailwind base, those are for Tailwind v3 and do not apply to v4 .
Utility Class Basics and the className Prop
Utility classes are single-purpose CSS classes. Instead of writing a custom class like .card-title, you apply text-lg font-semibold text-gray-900 directly. This feels unusual at first, but it removes the need to invent class names and switch between files.
// app/components/Badge.tsx
export default function Badge() {
return (
<span className="inline-flex items-center rounded-full bg-blue-100 px-3 py-1 text-sm font-medium text-blue-800">
New
</span>
);
}
Browser shows: A small pill-shaped badge with a light blue background and dark blue text. The classes inline-flex, rounded-full, px-3, and py-1 control layout and spacing.
How it works: The className prop accepts a string of space-separated class names. Tailwind generates each one as a small CSS rule. px-3 sets left and right padding. py-1 sets top and bottom padding. rounded-full makes the corners fully round. You combine them like building blocks.
Responsive Design with sm, md, and lg Prefixes
Tailwind is mobile-first by default. Unprefixed utilities apply to all screen sizes. Responsive prefixes like sm:, md:, and lg: apply styles at larger breakpoints. This means you design for small screens first, then add adjustments for tablets and desktops.
// app/components/ResponsiveGrid.tsx
export default function ResponsiveGrid() {
return (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
<div className="rounded bg-gray-100 p-4">Item 1</div>
<div className="rounded bg-gray-100 p-4">Item 2</div>
<div className="rounded bg-gray-100 p-4">Item 3</div>
<div className="rounded bg-gray-100 p-4">Item 4</div>
</div>
);
}
Browser shows: On a phone, the items stack in one column. On a tablet (768px and wider), they form two columns. On a desktop (1024px and wider), they form four columns.
How it works: grid-cols-1 is the base style. sm:grid-cols-2 overrides it at 640px and wider. lg:grid-cols-4 overrides it again at 1024px and wider. The gap-4 class adds space between items at all sizes. The order of prefixes in the class string does not matter, but the breakpoint order matters in Tailwind's generated CSS.
Hover, Focus, and Dark Mode States
Tailwind provides state variants that apply styles only when a condition is true. The most common are hover: for mouse hover and focus: for keyboard focus. Dark mode uses the dark: variant.
// app/components/Button.tsx
export default function Button() {
return (
<button className="rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-400 dark:bg-blue-500 dark:hover:bg-blue-400">
Click me
</button>
);
}
Browser shows: The button is blue. On hover, it becomes darker. When focused with the keyboard, a ring appears around it. In dark mode, the button uses a lighter blue shade.
How it works: hover:bg-blue-700 applies the background color only when the mouse is over the button. focus:ring-2 adds a ring when the button has keyboard focus. The dark: prefix works by default in Tailwind v4 using the system's dark mode preference. If you need a manual toggle instead, you must add a custom variant in your CSS file .
Reusing Styles: Components vs Long Class Lists
Long class strings are normal in Tailwind, but they can become hard to read and maintain. The recommended solution is to extract a component, not to create custom CSS classes with @apply. A React component with a clear name is easier to reuse and reason about.
// app/components/PricingCard.tsx
type PricingCardProps = {
name: string;
price: string;
features: string[];
};
export default function PricingCard({ name, price, features }: PricingCardProps) {
return (
<div className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-700 dark:bg-gray-800">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">{name}</h3>
<p className="mt-2 text-3xl font-bold text-gray-900 dark:text-white">{price}</p>
<ul className="mt-4 space-y-2">
{features.map((feature) => (
<li key={feature} className="text-sm text-gray-600 dark:text-gray-300">
{feature}
</li>
))}
</ul>
</div>
);
}
How it works: The PricingCard component encapsulates the long class list once. You can reuse it with different props without repeating the classes. If the design changes, you update one file. This approach keeps your JSX clean and your styles consistent.
Comparing CSS Modules, Tailwind, and Global CSS
| Approach | How it works | Best for | Trade-off |
|---|---|---|---|
| Global CSS | One or more CSS files imported once, styles apply everywhere | Resets, typography, theme variables | Easy to create naming conflicts and unintended overrides |
| CSS Modules | CSS files scoped to a component using unique class names | Complex components with many custom styles | Extra file per component; class names are generated |
| Tailwind CSS | Utility classes applied directly in JSX | Rapid UI development, consistent spacing and colors | Long class strings; requires learning utility names |
How it works: Global CSS is still useful for base styles and CSS variables. CSS Modules are a good fit when you have a component with unique, complex styling that does not map cleanly to utilities. Tailwind is strongest for layout, spacing, typography, and common UI patterns. Many projects use all three together.
Common Mistakes and Best Practices
- Following v3 setup guides for a v4 project. Tailwind v4 removed the
tailwind.config.jsrequirement and replaced@tailwind basewith@import "tailwindcss". Using old instructions causes errors or missing styles . - Building class names dynamically. Tailwind scans for complete class strings.
text-${color}-500will not work because the scanner cannot see the full name. Use conditional expressions with complete class names:isError ? "text-red-500" : "text-green-500". - Using
@applyeverywhere.@applystill works in v4, but the Tailwind team recommends extracting components instead. Components are easier to test and give you props and TypeScript types . - Forgetting the mobile-first order. Put base styles first, then add
sm:,md:, andlg:overrides. If you writemd:flex flex, the unprefixedflexmay override your responsive style depending on CSS order. - Assuming dark mode works with a manual toggle by default. In Tailwind v4,
dark:uses the system preference by default. For a class-based toggle, you need a custom variant in your CSS file .
Real-World Example: A Responsive Pricing Section
This example builds a three-column pricing grid that collapses to one column on mobile. Each card uses a reusable component with Tailwind utilities.
// app/pricing/page.tsx
import PricingCard from "../components/PricingCard";
const plans = [
{
name: "Starter",
price: "₹0",
features: ["1 project", "Community support", "Basic analytics"],
},
{
name: "Pro",
price: "₹499",
features: ["10 projects", "Priority support", "Advanced analytics", "Custom domain"],
},
{
name: "Team",
price: "₹1,299",
features: ["Unlimited projects", "Dedicated support", "SSO", "Audit logs"],
},
];
export default function PricingPage() {
return (
<section className="mx-auto max-w-6xl px-4 py-12">
<h1 className="text-center text-3xl font-bold text-gray-900 dark:text-white">
Simple Pricing
</h1>
<div className="mt-8 grid grid-cols-1 gap-6 md:grid-cols-3">
{plans.map((plan) => (
<PricingCard
key={plan.name}
name={plan.name}
price={plan.price}
features={plan.features}
/>
))}
</div>
</section>
);
}
Line-by-line explanation:
max-w-6xllimits the section width on large screens.mx-autocenters it.px-4 py-12adds horizontal and vertical spacing.- The heading uses
text-3xl font-boldfor size and weight, anddark:text-whitefor dark mode. grid grid-cols-1 md:grid-cols-3creates one column on mobile and three columns on medium screens and larger.gap-6adds space between the cards at all sizes.- Each
PricingCardreceives its data as props. The long class list lives inside the component, not on the page.
Summary
- Tailwind CSS with Next.js is set up automatically by
create-next-app. For existing projects, installtailwindcssand@tailwindcss/postcss, then add@import "tailwindcss"toglobals.css. - Tailwind v4 uses a CSS-first approach. No
tailwind.config.jsis required for basic use. - Use utility classes directly in the
classNameprop, and combine them with responsive prefixes likesm:,md:, andlg:. - Hover and focus states use variants like
hover:andfocus:. Dark mode usesdark:and respects system preference by default. - Reuse styles by extracting React components, not by creating long
@applyrules. - Global CSS, CSS Modules, and Tailwind can coexist. Choose the tool that fits the job.
Now that your UI looks good and responds to screen sizes, the next step is controlling who can see it. Continue with Next.js Authentication.
Frequently Asked Questions
Does create-next-app install Tailwind automatically?
Yes. When you run create-next-app and accept the Tailwind option, it configures Tailwind v4 for you. It creates a globals.css file with @import "tailwindcss" and a postcss.config.mjs file with the correct plugin. You do not need to create a tailwind.config.js file for basic use.
Why are my Tailwind classes not working after setup?
Check three things: the @import "tailwindcss" line must be in the CSS file that your layout imports, the PostCSS config must use @tailwindcss/postcss, and you must restart the dev server after changing config files. Also check for dynamically constructed class names, which Tailwind cannot detect.
What is the difference between Tailwind v3 and v4 setup?
Tailwind v4 uses @import "tailwindcss" instead of three @tailwind directives. It does not require a tailwind.config.js file for basic use, and theme customization moves to a @theme block in CSS. The content array for file scanning is also removed because v4 detects files automatically.
How do I enable a manual dark mode toggle with Tailwind?
By default, dark: uses the system preference. For a manual toggle, add a custom variant in your CSS: @custom-variant dark (&:is(.dark *));. Then add or remove the dark class on the <html> element. This gives users control over the theme instead of relying on their operating system setting.
Can I use Tailwind classes in Server Components?
Yes. Tailwind is purely CSS and works identically in Server and Client Components. The classes are resolved at build time, not at runtime. You do not need to add "use client" just to use Tailwind. The only exception is when you need interactive behavior like hover states driven by JavaScript, which still works with CSS variants.
Practice Exercises
Easy: Style a heading with Tailwind
Create a heading that uses text-2xl, font-semibold, and text-gray-800. Add a hover state that changes the color to text-blue-600.
Show solution
// app/page.tsx
export default function HomePage() {
return (
<h1 className="text-2xl font-semibold text-gray-800 hover:text-blue-600">
Welcome
</h1>
);
}
The hover:text-blue-600 variant applies the blue color only on mouse hover.
Easy: Make a responsive card
Create a div that is full width on mobile, half width on medium screens, and one-third width on large screens. Use w-full, md:w-1/2, and lg:w-1/3.
Show solution
// app/page.tsx
export default function ResponsiveCard() {
return (
<div className="w-full rounded border p-4 md:w-1/2 lg:w-1/3">
Responsive card
</div>
);
}
The unprefixed w-full is the base style. The md: and lg: prefixes override it at larger breakpoints.
Medium: Build a dark-mode ready button
Create a button with bg-blue-600 and text-white. Add dark:bg-blue-400 and dark:text-gray-900 for dark mode.
Show solution
// app/components/Button.tsx
export default function Button() {
return (
<button className="rounded bg-blue-600 px-4 py-2 text-white dark:bg-blue-400 dark:text-gray-900">
Submit
</button>
);
}
The dark: variant applies the dark mode styles when the system preference or a manual class enables dark mode.
Challenge: Extract a reusable card component
Create a Card component that accepts title and children props. Use Tailwind classes for padding, border, and shadow. Use it twice on a page with different content.
Show solution
// app/components/Card.tsx
type CardProps = {
title: string;
children: React.ReactNode;
};
export default function Card({ title, children }: CardProps) {
return (
<div className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm">
<h2 className="text-lg font-semibold text-gray-900">{title}</h2>
<div className="mt-2 text-gray-600">{children}</div>
</div>
);
}
// app/page.tsx
import Card from "./components/Card";
export default function HomePage() {
return (
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
<Card title="First Card">
<p>This is the first card content.</p>
</Card>
<Card title="Second Card">
<p>This is the second card content.</p>
</Card>
</div>
);
}
The long class list lives in one component, and the page stays readable. The children prop lets you pass different content to each card.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
