CSS Modules are useful for component-level styles. But if you want some CSS to be loaded by every page, Next.js has support for that as well.
To load global CSS files, create a file called _app.js
under pages
and add the following content:
export default function App({ Component, pageProps }) { return <Component {...pageProps} /> }
This App
component is the top-level component which will be common across all the different pages. You can use this App
component to keep state when navigating between pages, for example.
Important: You need to restart the development server when you add pages/_app.js
. Press Ctrl + c to stop the server and run:
npm run dev
In Next.js, you can add global CSS files by importing them from pages/_app.js
. You cannot import global CSS anywhere else.
The reason that global CSS can't be imported outside of pages/_app.js
is that global CSS affects all elements on the page.
If you were to navigate from the homepage to the /posts/first-post
page, global styles from the homepage would affect /posts/first-post
unintentionally.
You can place the global CSS file anywhere and use any name. So let’s do the following:
styles
directory and create global.css
inside.a
tag.html, body { padding: 0; margin: 0; font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; line-height: 1.6; font-size: 18px; } * { box-sizing: border-box; } a { color: #0070f3; text-decoration: none; } a:hover { text-decoration: underline; } img { max-width: 100%; display: block; }
Finally, import it in pages/_app.js
:
import '../styles/global.css' export default function App({ Component, pageProps }) { return <Component {...pageProps} /> }
Now, if you access http://localhost:3000/posts/first-post, you’ll see that the styles are applied:
If it didn’t work: Make sure you restart the development server when you add
pages/_app.js
.
To summarize what we’ve learned so far:
*.module.css
in any component.pages/_app.js
.