To implement page-specific CSS in a Next.js application, you can use CSS Modules, which allow you to scope CSS locally to the component rather than globally. This is particularly useful for applying unique styles that only affect a single page without risking style leakage across your application.
Step 1: Create a CSS Module
Create a CSS file with a module suffix, for example, BlogPage.module.css
, in the same directory as your page component.
/* app/blog/BlogPage.module.css */
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.title {
color: #333;
font-size: 24px;
}
.content {
font-size: 16px;
color: #666;
}
JavaScriptStep 2: Import the CSS Module in Your Page Component
Next, import this CSS module into your specific page component where you want to apply these styles.
// app/blog/page.tsx
import styles from './BlogPage.module.css';
export default function BlogPage() {
return (
<div className={styles.container}>
<h1 className={styles.title}>Welcome to Our Blog</h1>
<p className={styles.content}>Here you will find the latest updates and insights.</p>
</div>
);
}
JavaScriptBenefits of Using CSS Modules
- Local Scope: CSS classes are locally scoped to the component and do not conflict with other styles in the application.
- Maintenance and Refactoring: Easier to maintain and update styles without affecting other parts of the application.
- Code Splitting: Next.js automatically code-splits CSS so that styles are only loaded when the component is rendered.