Next.js Tutorial
- Next.js Introduction
- Next.js Installation
- Project Structure
- Pages & Routing
- Dynamic Routing
- Linking & Navigating
- Data Fetching (SSR)
- Data Fetching (SSG)
- Client-Side Rendering
- API Routes
- Layouts & Components
- Styling
- Image Optimization
- Font Optimization
- Script Optimization
- Middleware
- Environment Variables
- Error Handling
- Authentication
- React Server Components
- Server Actions
- Suspense & Streaming
- Caching & Revalidation
- TypeScript Integration
- Deployment
CSS & Styling in Next.js
Next.js provides diverse and highly optimized methods for styling your application out of the box. You can use Everything from traditional Global CSS to CSS Modules, Sass, or utility-first frameworks like Tailwind CSS.
1. Global CSS
Traditional global CSS stylesheets apply styles across your entire application. In Next.js, you typically define a globals.css file and import it at the uppermost level of your app.
- App Router: Import it inside
app/layout.js. - Pages Router: Import it inside
pages/_app.js.
// app/layout.js
import './globals.css';
export default function RootLayout({ children }) {
// ...
}2. CSS Modules (The Default Approach)
If you write standard CSS, you risk "class name collisions" where a `.btn` style in one component breaks a `.btn` style in another. CSS Modules automatically scopes CSS to the component level by generating unique class names.
Simply name your file ending in .module.css.
/* Button.module.css */
.error {
color: white;
background-color: red;
padding: 10px;
}
Then import it directly into your component as an object:
import styles from './Button.module.css';
export default function ErrorButton() {
// Renders a class like: class="Button_error__a9fG"
return <button className={styles.error}>Delete Data</button>;
}
3. Tailwind CSS (Recommended)
Next.js explicitly endorses Tailwind CSS, and it is the default option when running `create-next-app`. Tailwind provides utility classes to rapidly design components without switching files.
export default function Card() {
return (
<div className="max-w-md mx-auto bg-white rounded-xl shadow-md overflow-hidden p-6 mt-4">
<h2 className="text-xl font-bold text-gray-800">Tailwind Card</h2>
<p className="text-gray-600 mt-2">This is styled entirely without writing custom CSS.</p>
</div>
);
}4. CSS-in-JS (Styled-components, Emotion)
While popular in pure React, CSS-in-JS libraries can require extra configurational overhead in Next.js—especially when using Server Components, since libraries like styled-components require browser runtime execution to generate styles.
If you use them, you must ensure their components are evaluated as Client Components using 'use client'.
Conclusion
CSS Modules offer great scoping out of the box, and Tailwind provides extreme velocity. Next.js's real power, however, comes from its optimizations. In the next section, we'll look at the incrediblenext/image component.