CSS Modules and global CSS

Beginner · 16 min

Style Next.js App Router pages with CSS Modules for scoped classes and global CSS for the truly global, and learn how import order decides CSS order.

Before thisPages and layouts

Leon van Zyl · 16 min

CSS Modules and global CSS

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Leon van ZylReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A file named `something.module.css` is a CSS Module: importing it gives you an object whose keys are your class names, and the generated class names are unique, so two files can both define `.title` without clashing.
  • Global CSS is just a normal stylesheet imported into a layout; imported in the root layout it applies to every route.
  • Next.js does not remove a global stylesheet when you leave the route that imported it, so use global CSS only for styles that really are global.
  • In production the order of your CSS follows the order of your imports, and development can order it differently, so check the output of `next build` when two rules compete.
  • The docs recommend Tailwind for most styling and CSS Modules for component-specific styles that utilities do not cover.

The problem with one big stylesheet

Plain CSS has one namespace. Write .title { color: tomato } in the blog page and .title { font-size: 3rem } in the pricing page, and every .title on the site gets both. Teams solve this by inventing naming rules and hoping everyone follows them.

CSS Modules solve it in the build step instead. You write ordinary CSS, and the build tool renames your classes so they cannot collide. The css roadmap covers the idea in general. This lesson is about how Next.js wires it up.

A CSS Module, start to finish

Name the file with .module.css and put it next to the component that uses it.

/* app/blog/blog.module.css */
.blog {
  padding: 24px;
}
// app/blog/page.tsx
import styles from './blog.module.css'

export default function Page() {
  return <main className={styles.blog}></main>
}

The import gives you an object. styles.blog is a string holding the generated class name, so it is what you put in className. The docs describe it this way: CSS Modules locally scope CSS by generating unique class names. You write .blog; the browser sees something unique to that file.

This works in Server Components. There is no "use client" involved, because the result is a string and a stylesheet, not JavaScript that has to run in the browser.

Global CSS

Sometimes you do want a rule that hits everything: a page background, a box-sizing reset, the base styles Tailwind injects. That is a normal stylesheet with no .module in the name. Import it once in the root layout.

/* app/global.css */
body {
  padding: 20px 20px 60px;
  max-width: 680px;
  margin: 0 auto;
}
// app/layout.tsx
import './global.css'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}

Imported in the root layout, those styles apply to every route. Global styles can technically be imported into any layout, page, or component inside app, and that is where trouble starts. The docs explain why: Next.js integrates with React’s built-in stylesheet support so that styles work with Suspense, and as a result it does not currently remove a stylesheet when you move between routes. A global rule you imported for one page keeps applying on the next. The docs’ advice is to reserve global CSS for truly global things.

Stylesheets from packages

If a package ships a stylesheet, import it like any other file. The docs show this with Bootstrap:

// app/layout.tsx
import 'bootstrap/dist/css/bootstrap.css'

External stylesheets can be imported anywhere in app, including in colocated components. In React 19 you can also render a <link rel="stylesheet" href="..." /> directly.

Why import order matters

A stylesheet is not a set of independent files in production. Next.js merges and chunks your CSS during next build, and the order of the result follows the order of your imports. The docs give an example: base-button.module.css ends up ahead of page.module.css because the page imports BaseButton before it imports its own module.

When two rules have the same specificity, the later one wins. That means import order can decide which one wins. The docs add a warning that CSS ordering can behave differently in development, and tell you to check the next build result to confirm the final order.

The docs’ recommendations for keeping this predictable:

  • Keep CSS imports in one entry file where you can.
  • Import global styles and the Tailwind stylesheet in the root of the app.
  • Use a consistent naming convention for modules, such as <name>.module.css beside <name>.tsx.
  • Extract shared styles into shared components so the same import is not repeated.
  • Turn off linters that auto-sort imports, like ESLint’s sort-imports, because they can reorder your CSS.
  • If you need to change how CSS is chunked, there is a cssChunking option in next.config.js.

In production, CSS also loads with JavaScript disabled. In development, updates apply instantly through Fast Refresh, which does need JavaScript.

Which one to reach for

The docs recommend Tailwind for most styling, CSS Modules for component-specific styles when utilities are not enough, and global CSS only for truly global rules. The next lesson sets up Tailwind. React’s own comparison of styling approaches is in styling approaches for React, and the css roadmap covers the language underneath all of it.

What the video covers

Leon van Zyl’s video is from May 2023, made for Next.js 13. Per its title and the chapters recorded when it was sourced, it walks through global CSS, CSS Modules, and inline styles in the App Router, and also touches Tailwind and fonts. We could not read a transcript, so this lesson does not claim more than that. Two caveats. It shows the Tailwind v3 setup, which is not the current setup (see the next lesson). And import ordering and Sass are not what the video is about, so the prose above is where those come from. The mechanics of .module.css and global CSS are unchanged since the video.

Where this fits

You can now scope a style to a component or apply it everywhere. Next: Tailwind CSS in Next.js, the approach the docs recommend first.

Check yourself

  1. 01Why can two components each define a `.card` class in their own `.module.css` file without conflict?

    CSS Modules generate a unique class name for each file's classes. You reference the class through the imported `styles` object, so the name you write in the CSS is never the name that reaches the browser.

  2. 02Where do you import a global stylesheet so it applies to the whole app, and why is that a bad place for component styles?

    In the root layout. A global stylesheet imported anywhere is not removed when you leave the route, so styles meant for one page can end up affecting another.

  3. 03Two stylesheets set the same property on one element and it looks right in `next dev` but wrong in production. What do you check first?

    The import order. In production Next.js merges stylesheets and orders them by where they are imported, and the order in development can differ, so verify against a `next build` output.

  4. 04Can you import `bootstrap/dist/css/bootstrap.css` from a component?

    Yes. The docs say stylesheets from external packages can be imported anywhere in the `app` directory, including in colocated components.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark