Skip to content

CSS

Next.js 提供了几种在你的应用中使用 CSS 的方法,包括:

¥Next.js provides several ways to use CSS in your application, including:

CSS 模块

¥CSS Modules

CSS 模块通过生成唯一的类名在本地范围 CSS。这允许你在不同的文件中使用相同的类,而不必担心命名冲突。

¥CSS Modules locally scope CSS by generating unique class names. This allows you to use the same class in different files without worrying about naming collisions.

要开始使用 CSS 模块,请创建一个扩展名为 .module.css 的新文件并将其导入到 app 目录内的任何组件中:

¥To start using CSS Modules, create a new file with the extension .module.css and import it into any component inside the app directory:

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

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

全局 CSS

¥Global CSS

你可以使用全局 CSS 在整个应用中应用样式。

¥You can use global CSS to apply styles across your application.

创建一个 app/global.css 文件并将其导入到根布局中,以便将样式应用于应用中的每个路由:

¥Create a app/global.css file and import it in the root layout to apply the styles to every route in your application:

css
body {
  padding: 20px 20px 60px;
  max-width: 680px;
  margin: 0 auto;
}
tsx
// These styles apply to every route in the application
import './global.css'

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

需要了解:全局样式可以导入到 app 目录内的任何布局、页面或组件中。但是,由于 Next.js 使用 React 内置的样式表支持与 Suspense 集成,因此在路由之间导航时,此功能目前不会删除样式表,这可能会导致冲突。我们建议使用全局样式来实现真正的全局 CSS,使用 CSS 模块 来实现作用域 CSS。

¥Good to know: Global styles can be imported into any layout, page, or component inside the app directory. However, since Next.js uses React's built-in support for stylesheets to integrate with Suspense, this currently does not remove stylesheets as you navigate between routes which can lead to conflicts. We recommend using global styles for truly global CSS, and CSS Modules for scoped CSS.

外部样式表

¥External stylesheets

外部包发布的样式表可以导入到 app 目录中的任何位置,包括共置组件:

¥Stylesheets published by external packages can be imported anywhere in the app directory, including colocated components:

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

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

需要了解:在 React 19 中,<link rel="stylesheet" href="..." /> 也可以使用。请参阅 React link 文档 了解更多信息。

¥Good to know: In React 19, <link rel="stylesheet" href="..." /> can also be used. See the React link documentation for more information.

排序和合并

¥Ordering and Merging

Next.js 通过自动分块(合并)样式表来在生产构建期间优化 CSS。CSS 的顺序取决于你在代码中导入样式的顺序。

¥Next.js optimizes CSS during production builds by automatically chunking (merging) stylesheets. The order of your CSS depends on the order you import styles in your code.

例如,由于 <BaseButton>page.module.css 之前导入,因此 base-button.module.css 将排在 page.module.css 之前:

¥For example, base-button.module.css will be ordered before page.module.css since <BaseButton> is imported before page.module.css:

tsx
import { BaseButton } from './base-button'
import styles from './page.module.css'

export default function Page() {
  return <BaseButton className={styles.primary} />
}
tsx
import styles from './base-button.module.css'

export function BaseButton() {
  return <button className={styles.primary} />
}

建议

¥Recommendations

要保持 CSS 排序可预测:

¥To keep CSS ordering predictable:

  • 尝试将 CSS 导入包含在单个 JavaScript 或 TypeScript 入口文件中。

    ¥Try to contain CSS imports to a single JavaScript or TypeScript entry file

  • 在应用的根目录中导入全局样式和 Tailwind 样式表。

    ¥Import global styles and Tailwind stylesheets in the root of your application.

  • 对于嵌套组件,请使用 CSS 模块代替全局样式。

    ¥Use CSS Modules instead of global styles for nested components.

  • 为 CSS 模块使用一致的命名约定。例如,使用 <name>.module.css 而不是 <name>.tsx

    ¥Use a consistent naming convention for your CSS modules. For example, using <name>.module.css over <name>.tsx.

  • 将共享样式提取到共享组件中,以避免重复导入。

    ¥Extract shared styles into shared components to avoid duplicate imports.

  • 关闭自动排序导入的 linters 或格式化程序,例如 ESLint 的 sort-imports

    ¥Turn off linters or formatters that auto-sort imports like ESLint’s sort-imports.

  • 你可以使用 next.config.js 中的 cssChunking 选项来控制 CSS 的分块方式。

    ¥You can use the cssChunking option in next.config.js to control how CSS is chunked.

开发环境 vs 生产环境

¥Development vs Production

  • 在开发环境中(next dev),CSS 更新会立即应用到 快速刷新 中。

    ¥In development (next dev), CSS updates apply instantly with Fast Refresh.

  • 在生产环境中(next build),所有 CSS 文件都会自动合并成多个经过压缩和代码拆分的 .css 文件,以确保每个路由加载的 CSS 量最少。

    ¥In production (next build), all CSS files are automatically concatenated into many minified and code-split .css files, ensuring the minimal amount of CSS is loaded for a route.

  • 在生产环境中禁用 JavaScript 后,CSS 仍会加载,但在开发环境中,JavaScript 是快速刷新所必需的。

    ¥CSS still loads with JavaScript disabled in production, but JavaScript is required in development for Fast Refresh.

  • CSS 排序在开发过程中可能会有所不同,请务必检查构建 (next build) 以验证最终的 CSS 顺序。

    ¥CSS ordering can behave differently in development, always ensure to check the build (next build) to verify the final CSS order.