Tailwind CSS
Tailwind CSS 是一个实用程序优先的 CSS 框架,与 Next.js 配合得非常好。
¥Tailwind CSS is a utility-first CSS framework that works exceptionally well with Next.js.
安装 Tailwind
¥Installing Tailwind
安装 Tailwind CSS 包并运行 init
命令以生成 tailwind.config.js
和 postcss.config.js
文件:
¥Install the Tailwind CSS packages and run the init
command to generate both the tailwind.config.js
and postcss.config.js
files:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
配置 Tailwind
¥Configuring Tailwind
在 tailwind.config.js
内,添加将使用 Tailwind CSS 类名的文件的路径:
¥Inside tailwind.config.js
, add paths to the files that will use Tailwind CSS class names:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./app/**/*.{js,ts,jsx,tsx,mdx}', // Note the addition of the `app` directory.
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
// Or if using `src` directory:
'./src/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {},
},
plugins: [],
}
你不需要修改 postcss.config.js
。
¥You do not need to modify postcss.config.js
.
导入样式
¥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:
@tailwind base;
@tailwind components;
@tailwind utilities;
在 根布局 (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.
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>
)
}
// 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.
export default function Page() {
return <h1 className="text-3xl font-bold underline">Hello, Next.js!</h1>
}
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.