Next.js - Global CSS



Next.js provide a separate global css file to declare CSS styles that affect all pages in an application. In this chapter we will learn how to apply global CSS to a Next.js application.

Next.js Global Styles

Global CSS refers to styles that apply to the entire application rather than being scoped to individual components. These styles are typically defined in a CSS file and imported at a central entry point, such as the _app.js file in a Next.js project.

Create a Global CSS File

If you are using App router for your Next.js project, you will already have global.css file in project's app folder. For page router you can find global css file inside the styles folder. Paste the following code in your global css file.

// /app/global.css

div {
    font-family: Arial, sans-serif;
    padding: 20px;
    background-color: #f9f9f9;
    border: 2px solid;
    border-radius: 10px;
    max-width: 400px;
}
  
h1 {
    color: #0070f3;

}
  
h2 {
    color: #333;
}

Import Global CSS

Importing of global CSS is done at layout component. This is a special component, that is visible in every routes and style applied to this component will applicable to all other components.

// app/layout.tsx

import './/globals.css'; // import CSS

interface RootLayoutProps {
  children: ReactNode;
}

export default function RootLayout({ children }: RootLayoutProps) {
  return (
    <html lang="en">
        <body>
            <header>
                <h1>Header Element</h1>
            </header>
            <main>{children}</main>
        </body>
    </html>
  );
}

Output

In the output, style applied is reflecting in every pages.

next.js-css-global-styling

Next.js Global Style Rules

  • You cannot directly import global CSS in components. Imports must be done at the root level.
  • Global CSS applies styles to every components in projects.
  • Only .css files are supported for Global CSS imports. Other preprocessors like Sass require configuration.
Advertisements