How to Use Global CSS in Next.js: Simple Guide
In Next.js, you add global CSS by importing your CSS file inside the
pages/_app.js file. This ensures the styles apply to the entire app and follow Next.js rules that only allow global CSS imports in this special file.Syntax
To use global CSS in Next.js, import your CSS file inside the pages/_app.js file. This file wraps all pages, so styles here apply globally.
Example parts:
import '../styles/globals.css': imports the global CSS file.function MyApp({ Component, pageProps }): custom app component.return <Component {...pageProps} />: renders the current page.
javascript
import '../styles/globals.css' export default function MyApp({ Component, pageProps }) { return <Component {...pageProps} /> }
Example
This example shows how to create a global CSS file and apply it to all pages by importing it in pages/_app.js. The global CSS sets the background color and font for the whole app.
javascript
/* styles/globals.css */ body { background-color: #f0f0f0; font-family: Arial, sans-serif; margin: 0; padding: 20px; } // pages/_app.js import '../styles/globals.css' export default function MyApp({ Component, pageProps }) { return <Component {...pageProps} /> } // pages/index.js export default function Home() { return <h1>Welcome to Next.js with Global CSS!</h1> }
Output
The page background is light gray with Arial font and 20px padding around the content. The heading 'Welcome to Next.js with Global CSS!' appears styled by the global CSS.
Common Pitfalls
Common mistakes when using global CSS in Next.js include:
- Importing global CSS files outside
pages/_app.jscauses build errors. - Trying to import global CSS in components or pages directly is not allowed.
- For component-level styles, use CSS modules instead of global CSS.
Always keep global CSS imports only in _app.js.
javascript
// Wrong: importing global CSS in a page (causes error) // pages/index.js import '../styles/globals.css' // ❌ Not allowed here export default function Home() { return <h1>Hello</h1> } // Right: import global CSS only in _app.js // pages/_app.js import '../styles/globals.css' // ✅ Correct place export default function MyApp({ Component, pageProps }) { return <Component {...pageProps} /> }
Quick Reference
Summary tips for using global CSS in Next.js:
- Place global CSS files in the
stylesfolder or anywhere in your project. - Import global CSS only inside
pages/_app.js. - Use CSS modules for component-specific styles.
- Restart the development server if you add new CSS files.
Key Takeaways
Import global CSS files only in the pages/_app.js file in Next.js.
Global CSS applies styles to the entire app, so use it for base styles.
Component-level styles should use CSS modules, not global CSS.
Importing global CSS outside _app.js causes build errors.
Restart the dev server after adding new CSS files to see changes.