Next.js CSS Modules demonstrates how to implement component-scoped styling solutions that prevent class name collisions across your application.
CSS Modules are supported natively in Next.js. Any file ending with the .module.css extension automatically scopes its styles to the importing component.
Define styles inside a .module.css file:
/* app/components/Card.module.css */
.cardContainer {
padding: 1.5rem;
border-radius: 0.5rem;
background-color: #ffffff;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
.titleText {
font-size: 1.25rem;
font-weight: 700;
color: #1f2937;
}
Import class names as JavaScript objects inside your component:
// app/components/Card.tsx
import styles from './Card.module.css';
export default function Card({ title, content }: { title: string; content: string }) {
return (
<div className={styles.cardContainer}>
<h3 className={styles.titleText}>{title}</h3>
<p className="mt-2 text-gray-600">{content}</p>
</div>
);
}
Tailwind CSS is pre-configured during create-next-app initialization. Utility classes are applied directly in utility strings:
// app/components/AlertBanner.tsx
export default function AlertBanner({ message }: { message: string }) {
return (
<div className="p-4 bg-yellow-50 border-l-4 border-yellow-400 text-yellow-800">
<p className="font-medium">{message}</p>
</div>
);
}
globals.css)Global CSS stylesheets should be imported exclusively inside the Root Layout (app/layout.tsx):
/* app/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
font-family: system-ui, -apple-system, sans-serif;
}
.css files inside nested sub-components or route views.Next.js supports CSS Modules, Tailwind CSS, and global stylesheets out of the box. Component-scoped styles maintain clean codebases as your application grows.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.