Tailwind CSS
Tailwind CSS 是一个实用优先的 CSS 框架,与 Next.js 完全兼容。本指南将引导你如何在 Next.js 应用中安装 Tailwind CSS。
¥Tailwind CSS is a utility-first CSS framework that is fully compatible with Next.js. This guide will walk you through how to install Tailwind CSS in your Next.js application.
安装 Tailwind
¥Installing Tailwind
安装必要的 Tailwind CSS 包:
¥Install the necessary Tailwind CSS packages:
npm install -D tailwindcss @tailwindcss/postcss postcss
需要了解:如果你使用
create-next-app
CLI 创建项目,Next.js 会提示你是否要安装 Tailwind 并自动配置项目。¥Good to know: If you're using the
create-next-app
CLI to create your project, Next.js will prompt if you'd like to install Tailwind and automatically configure the project.
配置 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:
从 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 项目,则还会有 升级 CLI 和 guide。
¥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:
@import 'tailwindcss';
在 自定义应用文件 (pages/_app.js
) 内,导入 globals.css
样式表以将样式应用到应用中的每个路由。
¥Inside the custom app file (pages/_app.js
), import the globals.css
stylesheet to apply the styles to every route in your application.
// These styles apply to every route in the application
import '@/styles/globals.css'
import type { AppProps } from 'next/app'
export default function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
使用类
¥Using Classes
安装 Tailwind CSS 并添加全局样式后,你可以在应用中使用 Tailwind 的实用程序类。
¥After installing Tailwind CSS and adding the global styles, you can use Tailwind's utility classes in your application.
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.