跳到內容

如何在您的應用程式中使用 CSS

Next.js 提供了幾種在您的應用程式中使用 CSS 的方式,包括

本頁面將引導您了解如何使用這些方法。

CSS Modules

CSS Modules 透過產生獨特的類別名稱,將 CSS 作用域限定於本地。這讓您可以在不同的檔案中使用相同的類別,而不用擔心衝突。

要開始使用 CSS Modules,請建立一個新的檔案,副檔名為 .module.css,並將其匯入到 app 目錄內部的任何元件中

app/blog/styles.module.css
.blog {
  padding: 24px;
}
app/blog/page.tsx
import styles from './styles.module.css'
 
export default function Page({ children }: { children: React.ReactNode }) {
  return <main className={styles.blog}>{children}</main>
}

Global CSS

您可以使用全域 CSS 來在您的應用程式中套用樣式。

要使用全域樣式,請建立一個新的 CSS 檔案,例如 app/global.css

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

在根版面配置 (app/layout.js) 中匯入該檔案,以將樣式套用到您應用程式中的每個路由

app/layout.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 Modules 用於作用域限定的 CSS。

Tailwind CSS

Tailwind CSS 是一個實用優先的 CSS 框架,可以與 Next.js 無縫整合。

安裝 Tailwind

要開始使用 Tailwind,請安裝必要的 Tailwind CSS 套件

終端機
npm install -D tailwindcss @tailwindcss/postcss postcss

設定 Tailwind

在專案根目錄中建立一個 postcss.config.mjs 檔案,並將 @tailwindcss/postcss 外掛程式新增到您的 PostCSS 設定中

postcss.config.mjs
/** @type {import('tailwindcss').Config} */
export default {
  plugins: {
    '@tailwindcss/postcss': {},
  },
}

使用 Tailwind

Tailwind 指令 新增到您的 全域樣式表

app/globals.css
@import 'tailwindcss';

然後,在 根版面配置 中匯入樣式

app/layout.tsx
import type { Metadata } from 'next'
 
// These styles apply to every route in the application
import './globals.css'
 
export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}

最後,您可以開始在您的應用程式中編寫 Tailwind 的實用類別。

app/page.tsx
export default function Page() {
  return <h1 className="text-3xl font-bold underline">Hello, Next.js!</h1>
}

Sass

Next.js 整合了 Sass,同時支援 .scss.sass 副檔名和語法。

您也可以透過 CSS Modules.module.scss.module.sass 副檔名,使用元件層級的 Sass。

安裝 Sass

要開始使用 Sass,請安裝 sass 套件

終端機
npm install --save-dev sass

自訂 Sass 選項

如果您想要設定您的 Sass 選項,請使用 sassOptions 選項,在 next.config.js 中。

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  sassOptions: {
    additionalData: `$var: red;`,
  },
}
 
export default nextConfig

CSS-in-JS

警告: 需要執行階段 JavaScript 的 CSS-in-JS 函式庫目前在 React 伺服器元件中不受支援。將 CSS-in-JS 與較新的 React 功能(如伺服器元件和串流)一起使用,需要函式庫作者支援最新版本的 React。

以下函式庫在 app 目錄中的用戶端元件中受到支援(依字母順序排列)

以下函式庫目前正在努力支援

如果您想要設定伺服器元件的樣式,我們建議使用 CSS Modules 或其他輸出 CSS 檔案的解決方案,例如 Tailwind CSS

設定 CSS-in-JS

要設定 CSS-in-JS,您需要

  1. 建立一個樣式註冊表,以收集渲染中的所有 CSS 規則。
  2. 使用 useServerInsertedHTML Hook,在任何可能使用它們的內容之前注入規則。
  3. 建立一個用戶端元件,在初始伺服器端渲染期間使用樣式註冊表包裝您的應用程式。

styled-jsx

要為您的應用程式設定 styled-jsx,請建立一個新的註冊表

app/registry.tsx
'use client'
 
import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { StyleRegistry, createStyleRegistry } from 'styled-jsx'
 
export default function StyledJsxRegistry({
  children,
}: {
  children: React.ReactNode
}) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://react.dev.org.tw/docs/hooks-reference.html#lazy-initial-state
  const [jsxStyleRegistry] = useState(() => createStyleRegistry())
 
  useServerInsertedHTML(() => {
    const styles = jsxStyleRegistry.styles()
    jsxStyleRegistry.flush()
    return <>{styles}</>
  })
 
  return <StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry>
}

然後,使用註冊表包裝您的 根版面配置

app/layout.tsx
import StyledJsxRegistry from './registry'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <StyledJsxRegistry>{children}</StyledJsxRegistry>
      </body>
    </html>
  )
}

styled-components

要使用 styled-components,請在 next.config.js 中啟用它

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  compiler: {
    styledComponents: true,
  },
}
 
export default nextConfig

然後,使用 styled-components API 建立一個全域註冊表元件,以收集渲染期間產生的所有 CSS 樣式規則,以及一個傳回這些規則的函式。然後使用 useServerInsertedHTML Hook,將註冊表中收集的樣式注入到根版面配置中的 <head> HTML 標籤中。

lib/registry.tsx
'use client'
 
import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'
 
export default function StyledComponentsRegistry({
  children,
}: {
  children: React.ReactNode
}) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://react.dev.org.tw/docs/hooks-reference.html#lazy-initial-state
  const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet())
 
  useServerInsertedHTML(() => {
    const styles = styledComponentsStyleSheet.getStyleElement()
    styledComponentsStyleSheet.instance.clearTag()
    return <>{styles}</>
  })
 
  if (typeof window !== 'undefined') return <>{children}</>
 
  return (
    <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
      {children}
    </StyleSheetManager>
  )
}

使用樣式註冊表元件包裝根版面配置的 children

app/layout.tsx
import StyledComponentsRegistry from './lib/registry'
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <StyledComponentsRegistry>{children}</StyledComponentsRegistry>
      </body>
    </html>
  )
}

外部樣式表

外部套件發布的樣式表可以匯入到 app 目錄中的任何位置,包括同級元件

app/layout.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>
  )
}

外部樣式表必須直接從 npm 套件匯入,或下載並與您的程式碼庫同級放置。您不能使用 <link rel="stylesheet" />