Next.js - Global CSS Support
Next.js - Global CSS Styles
Section titled “Next.js - Global CSS Styles”While component-scoped styles like CSS Modules are generally preferred, you often need some global styles for base resets, typography, layout defaults, or third-party library styling.
In Next.js (using the Pages Router), the standard way to include global CSS is by importing it into the pages/_app.js (or _app.tsx) file. This file acts as a wrapper around all your page components.
If you are using the App Router, global styles are typically imported into the root layout.js or layout.tsx file.
Let’s create a global stylesheet and apply it using the Pages Router approach.
First, create a styles directory at the root level (if it doesn’t exist) and add a file named globals.css:
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; background-color: #f0f0f0; /* Example background color */}
* { box-sizing: border-box;}
a { color: #0070f3; text-decoration: none;}
a:hover { text-decoration: underline;}
img { max-width: 100%; display: block;}This file contains typical reset rules, base font settings, link styling, and a light gray background color for the body.
Now, create or update the pages/_app.js file to import this global stylesheet:
// Import global styles hereimport '../styles/globals.css';
// This default export is required in a new `pages/_app.js` file.export default function MyApp({ Component, pageProps }) { // You can add layout components or providers here that wrap all pages return <Component {...pageProps} />;}Important: Global CSS can only be imported inside pages/_app.js. Importing global CSS files in other components is not allowed by default in Next.js to prevent unintended side effects. Use CSS Modules or other scoping mechanisms for component-level styles.
Running the Development Server
Section titled “Running the Development Server”If your server isn’t running, start it:
npm run dev
# Example Output:# ready - started server on 0.0.0.0:3000, url: http://localhost:3000# event - compiled client and server successfully ...Verify Output
Section titled “Verify Output”Open http://localhost:3000 in your browser. You should observe that the default browser styles have been overridden. The background color should be light gray (#f0f0f0), the font should match the stack defined in globals.css, and links should have the specified blue color and hover effect. These styles will apply consistently across all pages of your application because they were imported in _app.js.
Navigate to other pages (like the /posts/first-post page from the previous example) to confirm the global styles are applied everywhere.