tezvyn:

Global vs. Component CSS in React/Next.js

AI-drafted, machine-checkedSource: nextjs.orgbeginner

Treat CSS like any other module. Import global styles (like resets or Tailwind) once in your app's entry point. For component-specific styles, import a CSS Module file directly into your component to keep styles scoped and prevent conflicts.

WHY IT EXISTS: In traditional web development, CSS files were global, leading to complex and fragile stylesheets where a small change could break unrelated parts of the site. React's component-based architecture needed a way to encapsulate styles along with markup and logic, preventing these global conflicts.

THE MENTAL MODEL: Think of CSS in two categories: global and local. Global styles apply to your entire site (e.g., fonts, color schemes, CSS resets) and are loaded only once. Local styles are specific to a single component (e.g., the padding on a particular button) and live with that component's code, imported just like a helper function.

HOW IT WORKS: In a Next.js app, you import global CSS files (like globals.css) exclusively in the root layout file (app/layout.js). For component-level styling, you create a file named with a .module.css extension, like Button.module.css. Then, inside your component file (Button.js), you import it: import styles from './Button.module.css';. You apply classes using this imported object: <button className={styles.myButton}>. The build process automatically generates a unique class name to guarantee the style is scoped only to that component.

WHEN TO USE IT: This is the standard pattern for styling modern React and Next.js applications. Use global imports for foundational styles like fonts, resets, and utility-class frameworks like Tailwind CSS. Use CSS Modules for the vast majority of your component styling to ensure encapsulation and prevent style leakage.

WHEN NOT TO USE IT: Avoid importing any non-module CSS file into any component besides the top-level root layout. Doing so breaks the encapsulation model and can introduce hard-to-debug style conflicts and issues with loading order. While CSS-in-JS libraries exist for dynamic styling, CSS Modules cover most use cases effectively.

ONE CANONICAL EXAMPLE: To style a Card component, you would create Card.js and Card.module.css. Inside Card.module.css, you'd define .wrapper { border: 1px solid #eee; padding: 16px; }. Inside Card.js, you'd write import styles from './Card.module.css'; and use it in your JSX like .... This .wrapper class will not affect any other div on your site.

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.