Skip to content

Tailwind CSS

Tailwind CSS 是一个实用优先的 CSS 框架,与 Next.js 完全兼容。

¥Tailwind CSS is a utility-first CSS framework that is fully compatible with Next.js.

安装 Tailwind

¥Installing Tailwind

安装必要的 Tailwind CSS 包:

¥Install the necessary Tailwind CSS packages:

bash
npm install -D tailwindcss @tailwindcss/postcss postcss

配置 Tailwind

¥Configuring Tailwind

在项目根目录中创建 postcss.config.mjs 文件,并将 @tailwindcss/postcss 插件添加到 PostCSS 配置中:

¥Create a postcss.config.mjs file in the root of your project and add the @tailwindcss/postcss plugin to your PostCSS configuration:

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

Tailwind v4 开始,默认情况下无需任何配置。如果你确实需要配置 Tailwind,可以按照 官方文档 中的说明配置全局 CSS 文件。

¥As of Tailwind v4, there is zero configuration required by default. If you do need to configure Tailwind, you can follow the official documentation for configuring the global CSS file.

如果你已有 Tailwind v3 项目,则还会有 升级 CLIguide

¥There is also an upgrade CLI and guide if you have an existing Tailwind v3 project.

导入样式

¥Importing Styles

添加 Tailwind 将用来将其生成的样式注入到应用中的 全局样式表Tailwind CSS 指令,例如:

¥Add the Tailwind CSS directives that Tailwind will use to inject its generated styles to a Global Stylesheet in your application, for example:

css
@import 'tailwindcss';

根布局 (app/layout.tsx) 内,导入 globals.css 样式表以将样式应用到应用中的每个路由。

¥Inside the root layout (app/layout.tsx), import the globals.css stylesheet to apply the styles to every route in your application.

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>
  )
}
jsx
// These styles apply to every route in the application
import './globals.css'

export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

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

使用类

¥Using Classes

安装 Tailwind CSS 并添加全局样式后,你可以在应用中使用 Tailwind 的实用程序类。

¥After installing Tailwind CSS and adding the global styles, you can use Tailwind's utility classes in your application.

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

与 Turbopack 一起使用

¥Usage with Turbopack

从 Next.js 13.1 开始,Turbopack 支持 Tailwind CSS 和 PostCSS。

¥As of Next.js 13.1, Tailwind CSS and PostCSS are supported with Turbopack.

Next.js v15.3 中文网 - 粤ICP备13048890号