0
0
NextJSframework~5 mins

Global CSS in NextJS

Choose your learning style9 modes available
Introduction

Global CSS lets you apply styles that affect your whole website. It helps keep your design consistent everywhere.

You want the same font and colors on every page.
You need to style HTML elements like body, h1, or p globally.
You want to add a background color or reset default browser styles.
You want to include third-party CSS libraries like Bootstrap.
You want to define CSS variables for your entire app.
Syntax
NextJS
/* In your Next.js project, create a CSS file like styles/globals.css */

/* styles/globals.css */
body {
  margin: 0;
  font-family: Arial, sans-serif;
  background-color: #f0f0f0;
}

/* Then import it in your app entry file */

// app/layout.js (Next.js 13+ App Router)
import './globals.css';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

Global CSS files must be imported only once, usually in the root layout or _app.js.

Next.js requires global CSS imports to be in special files like app/layout.js or pages/_app.js.

Examples
This example sets a white background and black text for the whole site.
NextJS
/* styles/globals.css */
body {
  background-color: white;
  color: black;
}

// app/layout.js
import './globals.css';
This example styles all <h1> headings globally with a bigger font and dark blue color.
NextJS
/* styles/globals.css */
h1 {
  font-size: 2rem;
  color: darkblue;
}

// app/layout.js
import './globals.css';
Sample Program

This Next.js app uses a global CSS file to style the body and h1 elements. The background is a light teal color, text is dark teal, and the heading is centered with margin.

NextJS
/* styles/globals.css */
body {
  margin: 0;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background-color: #e0f7fa;
  color: #006064;
}

h1 {
  text-align: center;
  margin-top: 2rem;
}

// app/layout.js
import './globals.css';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <h1>Welcome to My Next.js Site</h1>
        {children}
      </body>
    </html>
  );
}
OutputSuccess
Important Notes

Global CSS affects all components and pages, so use it for shared styles only.

For component-specific styles, use CSS Modules or styled components instead.

Remember to keep your global CSS file organized to avoid conflicts.

Summary

Global CSS applies styles across your entire Next.js app.

Import your global CSS file once in app/layout.js or pages/_app.js.

Use global CSS for fonts, colors, and base element styles.