tailwind-css
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTailwind CSS v4
Tailwind CSS v4
Expert guidance for Tailwind CSS v4, CSS-first configuration, modern utility patterns, and type-safe component styling with tailwind-variants.
为Tailwind CSS v4提供专业指导,包括CSS优先配置、现代工具类模式,以及使用tailwind-variants实现类型安全的组件样式。
CSS-First Configuration
CSS优先配置
Tailwind CSS v4 eliminates in favor of CSS-only configuration. All configuration lives in CSS files using special directives.
tailwind.config.tsCore Directives:
- - Entry point that loads Tailwind
@import "tailwindcss" - - Define or extend design tokens
@theme { } - - Define tokens that should not generate utilities
@theme static { } - - Create custom utilities
@utility - - Define custom variants
@custom-variant
Minimal Example:
css
@import "tailwindcss";
@theme {
--color-brand: oklch(0.72 0.11 178);
--font-display: "Inter", sans-serif;
--spacing-edge: 1.5rem;
}All theme tokens defined with automatically become available as utility classes. For example, can be used as , , , etc.
@theme--color-brandbg-brandtext-brandborder-brandTailwind CSS v4 移除了,转而采用纯CSS配置。所有配置都通过特殊指令存放在CSS文件中。
tailwind.config.ts核心指令:
- - 加载Tailwind的入口点
@import "tailwindcss" - - 定义或扩展Design Tokens
@theme { } - - 定义不会生成工具类的令牌
@theme static { } - - 创建自定义工具类
@utility - - 定义自定义变体
@custom-variant
最简示例:
css
@import "tailwindcss";
@theme {
--color-brand: oklch(0.72 0.11 178);
--font-display: "Inter", sans-serif;
--spacing-edge: 1.5rem;
}所有通过定义的主题令牌会自动成为可用的工具类。例如,可被用作、、等。
@theme--color-brandbg-brandtext-brandborder-brandESLint Integration
ESLint集成
Use for Tailwind CSS v4 class validation and style enforcement.
eslint-plugin-better-tailwindcssCorrectness Rules (errors):
- - Detect classes that override each other
no-conflicting-classes - - Flag classes not registered with Tailwind
no-unknown-classes
Stylistic Rules (warnings):
- - Use standard v4 class names
enforce-canonical-classes - - Use abbreviated class versions
enforce-shorthand-classes - - Remove outdated class names
no-deprecated-classes - - Eliminate redundant declarations
no-duplicate-classes - - Clean up extra spacing
no-unnecessary-whitespace
Examples:
typescript
// ❌ Bad: separate padding
<div className="px-6 py-6">
// ✅ Good: shorthand
<div className="p-6">typescript
// ❌ Bad: separate width/height
<div className="w-6 h-6">
// ✅ Good: size utility
<div className="size-6">Run the project's ESLint check after modifying Tailwind classes to validate all changes across the codebase.
使用进行Tailwind CSS v4类的验证和样式规范检查。
eslint-plugin-better-tailwindcss正确性规则(错误级别):
- - 检测相互覆盖的类
no-conflicting-classes - - 标记未在Tailwind中注册的类
no-unknown-classes
样式规则(警告级别):
- - 使用标准v4类名
enforce-canonical-classes - - 使用缩写类版本
enforce-shorthand-classes - - 移除过时的类名
no-deprecated-classes - - 消除冗余声明
no-duplicate-classes - - 清理多余空格
no-unnecessary-whitespace
示例:
typescript
// ❌ 不良写法:分开设置内边距
<div className="px-6 py-6">
// ✅ 推荐写法:简写形式
<div className="p-6">typescript
// ❌ 不良写法:分开设置宽高
<div className="w-6 h-6">
// ✅ 推荐写法:尺寸工具类
<div className="size-6">修改Tailwind类后,运行项目的ESLint检查,以验证代码库中所有变更的正确性。
Coding Preferences
编码偏好
Layout and Spacing
布局与间距
Use for flex/grid spacing, not /:
gapspace-xspace-yThe utilities handle wrapping correctly, while utilities break when flex/grid items wrap to multiple lines.
gapspace-*typescript
// ✅ Good: gap handles wrapping
<div className="flex gap-4">
// ❌ Bad: breaks when items wrap
<div className="flex space-x-4">Prefer over separate / for equal dimensions:
size-*w-*h-*typescript
// ✅ Good: concise
<div className="size-16">
// ❌ Bad: redundant
<div className="w-16 h-16">Always use instead of :
min-h-dvhmin-h-screenDynamic viewport height () accounts for mobile browser chrome, while units ignore it and cause layout issues on mobile Safari.
dvhvhtypescript
// ✅ Good: works on mobile Safari
<main className="min-h-dvh">
// ❌ Bad: buggy on mobile Safari
<main className="min-h-screen">Prefer top/left margins over bottom/right:
Consistent directionality improves layout predictability.
typescript
// ✅ Good: top margin
<div className="mt-4">
// ❌ Avoid: bottom margin (unless needed)
<div className="mb-4">Use padding on parent containers instead of bottom margins on last child:
Padding provides consistent spacing without needing selectors.
:last-childtypescript
// ✅ Good: padding on parent
<section className="pb-8">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</section>
// ❌ Avoid: margin on children
<section>
<div className="mb-4">Item 1</div>
<div className="mb-4">Item 2</div>
<div>Item 3</div>
</section>For max-widths, prefer container scale over pixel values:
typescript
// ✅ Good: semantic container size
<div className="max-w-2xl">
// ❌ Avoid: arbitrary pixel value
<div className="max-w-[672px]">使用设置flex/grid间距,而非/:
gapspace-xspace-ygapspace-*typescript
// ✅ 推荐写法:gap适配换行
<div className="flex gap-4">
// ❌ 不良写法:项换行时失效
<div className="flex space-x-4">尺寸相同时,优先使用而非分开的/:
size-*w-*h-*typescript
// ✅ 推荐写法:简洁
<div className="size-16">
// ❌ 不良写法:冗余
<div className="w-16 h-16">始终使用而非:
min-h-dvhmin-h-screen动态视口高度()会考虑移动浏览器的界面元素,而单位会忽略这些元素,导致在移动端Safari上出现布局问题。
dvhvhtypescript
// ✅ 推荐写法:适配移动端Safari
<main className="min-h-dvh">
// ❌ 不良写法:在移动端Safari存在bug
<main className="min-h-screen">优先使用上/左外边距,而非下/右外边距:
一致的方向能提升布局的可预测性。
typescript
// ✅ 推荐写法:上外边距
<div className="mt-4">
// ❌ 避免使用:下外边距(除非必要)
<div className="mb-4">在父容器上使用内边距,而非在最后一个子元素上使用下外边距:
内边距能提供一致的间距,无需使用选择器。
:last-childtypescript
// ✅ 推荐写法:父容器设置内边距
<section className="pb-8">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</section>
// ❌ 避免使用:子元素设置外边距
<section>
<div className="mb-4">Item 1</div>
<div className="mb-4">Item 2</div>
<div>Item 3</div>
</section>最大宽度优先使用容器尺寸等级,而非像素值:
typescript
// ✅ 推荐写法:语义化容器尺寸
<div className="max-w-2xl">
// ❌ 避免使用:任意像素值
<div className="max-w-[672px]">Typography
排版
Avoid classes; use line height modifiers:
leading-*Tailwind v4 supports inline line height modifiers with the syntax.
text-{size}/{leading}typescript
// ✅ Good: combined size and line height
<p className="text-base/7">
// ❌ Bad: separate utilities
<p className="text-base leading-7">Font Size Reference:
| Class | Size |
|---|---|
| 12px |
| 14px |
| 16px |
| 18px |
| 20px |
避免使用类;使用行高修饰符:
leading-*Tailwind v4支持通过语法设置行高修饰符。
text-{size}/{leading}typescript
// ✅ 推荐写法:字号与行高结合
<p className="text-base/7">
// ❌ 不良写法:分开设置工具类
<p className="text-base leading-7">字号参考:
| 类名 | 尺寸 |
|---|---|
| 12px |
| 14px |
| 16px |
| 18px |
| 20px |
Colors and Opacity
颜色与透明度
Use opacity modifier syntax, not separate opacity utilities:
All utilities were removed in Tailwind v4. Use the modifier syntax instead.
*-opacity-*typescript
// ✅ Good: opacity modifier
<div className="bg-red-500/60">
// ❌ Bad: removed in v4
<div className="bg-red-500 bg-opacity-60">Prefer design tokens over arbitrary hex values:
Check the project's configuration before using arbitrary color values.
@themetypescript
// ✅ Good: theme token
<div className="bg-brand">
// ❌ Avoid: arbitrary hex (check theme first)
<div className="bg-[#4f46e5]">使用透明度修饰符语法,而非单独的透明度工具类:
所有工具类在Tailwind v4中已被移除,请改用修饰符语法。
*-opacity-*typescript
// ✅ 推荐写法:透明度修饰符
<div className="bg-red-500/60">
// ❌ 不良写法:v4中已移除
<div className="bg-red-500 bg-opacity-60">优先使用Design Tokens,而非任意十六进制值:
使用任意颜色值前,请先查看项目的配置。
@themetypescript
// ✅ 推荐写法:主题令牌
<div className="bg-brand">
// ❌ 避免使用:任意十六进制值(先检查主题配置)
<div className="bg-[#4f46e5]">Border Radius
边框圆角
Tailwind v4 renamed border radius utilities:
| v3 | v4 (equivalent) | Size |
|---|---|---|
| | 2px |
| | 4px |
| | 6px |
| | 8px |
Use the v4 names when writing new code.
Tailwind v4重命名了边框圆角工具类:
| v3 类名 | v4 等效类名 | 尺寸 |
|---|---|---|
| | 2px |
| | 4px |
| | 6px |
| | 8px |
编写新代码时请使用v4的类名。
Gradients
渐变
Tailwind v4 renamed gradient utilities and added new gradient types.
Use , not :
bg-linear-*bg-gradient-*typescript
// ✅ Good: v4 syntax
<div className="bg-linear-to-r from-blue-500 to-purple-500">
// ❌ Bad: removed in v4
<div className="bg-gradient-to-r from-blue-500 to-purple-500">New gradient types:
- - Radial gradients
bg-radial - - Conic gradients
bg-conic
Example:
typescript
<div className="bg-radial from-blue-500 to-purple-500">
<div className="bg-conic from-red-500 via-yellow-500 to-green-500">Tailwind v4重命名了渐变工具类,并新增了新的渐变类型。
使用,而非:
bg-linear-*bg-gradient-*typescript
// ✅ 推荐写法:v4语法
<div className="bg-linear-to-r from-blue-500 to-purple-500">
// ❌ 不良写法:v4中已移除
<div className="bg-gradient-to-r from-blue-500 to-purple-500">新增渐变类型:
- - 径向渐变
bg-radial - - 锥形渐变
bg-conic
示例:
typescript
<div className="bg-radial from-blue-500 to-purple-500">
<div className="bg-conic from-red-500 via-yellow-500 to-green-500">Arbitrary Values
任意值
Always prefer Tailwind's predefined scale:
Check the project's configuration for available tokens before using arbitrary values.
@themetypescript
// ✅ Good: predefined scale
<div className="ml-4">
// ❌ Avoid: arbitrary pixel value
<div className="ml-[16px]">General rule: Prefer sizing scale over pixel values. Three similar lines of code is better than a premature abstraction.
始终优先使用Tailwind的预定义尺寸等级:
使用任意值前,请先查看项目的配置中的可用令牌。
@themetypescript
// ✅ 推荐写法:预定义等级
<div className="ml-4">
// ❌ 避免使用:任意像素值
<div className="ml-[16px]">通用规则: 优先使用尺寸等级而非像素值。三段相似的代码比过早的抽象更好。
Class Merging
类合并
The common pattern is a utility combining + .
cnclsxtailwind-mergeUse for:
cn- Static constants:
const CARD_BASE = cn("fixed classes") - Conditional classes:
cn("base", condition && "conditional") - Dynamic merging:
cn(baseClasses, className) - Conflict resolution: →
cn("p-4", "p-6")"p-6"
Do NOT use for:
cn- Static strings in attributes:
classNameclassName="fixed classes"
Examples:
typescript
// ✅ Good: static string in className
<button className="rounded-lg px-4 py-2 font-medium bg-blue-600">
// ✅ Good: static constant with cn
const CARD_BASE = cn("rounded-lg border border-gray-300 p-4");
<div className={CARD_BASE} />
// ✅ Good: conditional with cn
<button className={cn(
"rounded-lg px-4 py-2 font-medium",
isActive ? "bg-blue-600" : "bg-gray-700",
disabled && "opacity-50"
)} />
// ❌ Bad: unnecessary cn for static className attribute
<button className={cn("rounded-lg px-4 py-2 font-medium")} />常见模式是使用工具类结合 + 。
cnclsxtailwind-merge使用的场景:
cn- 静态常量:
const CARD_BASE = cn("fixed classes") - 条件类:
cn("base", condition && "conditional") - 动态合并:
cn(baseClasses, className) - 冲突解决:→
cn("p-4", "p-6")"p-6"
不使用的场景:
cn- 属性中的静态字符串:
classNameclassName="fixed classes"
示例:
typescript
// ✅ 推荐写法:className中使用静态字符串
<button className="rounded-lg px-4 py-2 font-medium bg-blue-600">
// ✅ 推荐写法:使用cn定义静态常量
const CARD_BASE = cn("rounded-lg border border-gray-300 p-4");
<div className={CARD_BASE} />
// ✅ 推荐写法:使用cn处理条件类
<button className={cn(
"rounded-lg px-4 py-2 font-medium",
isActive ? "bg-blue-600" : "bg-gray-700",
disabled && "opacity-50"
)} />
// ❌ 不良写法:静态className属性不必要地使用cn
<button className={cn("rounded-lg px-4 py-2 font-medium")} />Image Sizing
图片尺寸
Use Tailwind size classes instead of pixel values for components.
Imagetypescript
// ✅ Good: Tailwind units
<Image src={src} alt={alt} className="size-16" />
<Image src={src} alt={alt} className="w-24 h-auto" />
// ❌ Bad: pixel values
<Image src={src} alt={alt} width={64} height={64} />为组件使用Tailwind尺寸类,而非像素值。
Imagetypescript
// ✅ 推荐写法:Tailwind单位
<Image src={src} alt={alt} className="size-16" />
<Image src={src} alt={alt} className="w-24 h-auto" />
// ❌ 不良写法:像素值
<Image src={src} alt={alt} width={64} height={64} />Z-Index
Z-Index
Define z-index values as CSS custom properties in , then reference them with the syntax.
@themez-(--z-*)Never use arbitrary z-index numbers:
typescript
// ✅ Good: theme z-index value
<div className="z-(--z-modal)">
<div className="z-(--z-sticky)">
// ❌ Bad: arbitrary z-index numbers
<div className="z-[100]">
<div className="z-[9999]">Define z-index tokens in CSS:
css
@theme {
--z-base: 0;
--z-sticky: 10;
--z-modal: 100;
--z-tooltip: 1000;
}在中以CSS自定义属性的形式定义z-index值,然后通过语法引用。
@themez-(--z-*)切勿使用任意z-index数字:
typescript
// ✅ 推荐写法:主题z-index值
<div className="z-(--z-modal)">
<div className="z-(--z-sticky)">
// ❌ 不良写法:任意z-index数字
<div className="z-[100]">
<div className="z-[9999]">在CSS中定义z-index令牌:
css
@theme {
--z-base: 0;
--z-sticky: 10;
--z-modal: 100;
--z-tooltip: 1000;
}Dark Mode
深色模式
Use the plain variant for dark mode styles.
dark:Pattern:
Write light mode styles first, then add dark mode overrides.
typescript
// ✅ Good: light mode first, then dark override
<div className="bg-white text-gray-900 dark:bg-gray-900 dark:text-white">
// ❌ Avoid: dark mode first (less readable)
<div className="dark:bg-gray-900 dark:text-white bg-white text-gray-900">使用纯变体设置深色模式样式。
dark:模式:
先编写浅色模式样式,再添加深色模式覆盖样式。
typescript
// ✅ 推荐写法:先浅色模式,再深色覆盖
<div className="bg-white text-gray-900 dark:bg-gray-900 dark:text-white">
// ❌ 避免使用:先深色模式(可读性差)
<div className="dark:bg-gray-900 dark:text-white bg-white text-gray-900">CSS Modules
CSS Modules
Use CSS Modules only as a last resort for complex CSS that cannot be easily written with Tailwind classes.
All files must include at the top to enable Tailwind utilities and theme tokens inside the module.
.module.css@reference "#tailwind";Example:
css
/* component.module.css */
@reference "#tailwind";
.component {
/* Complex CSS that can't be expressed with Tailwind utilities */
/* Can still use Tailwind utilities and theme tokens */
}仅在无法用Tailwind类轻松实现复杂CSS时,才作为最后手段使用CSS Modules。
所有文件必须在顶部包含,以在模块中启用Tailwind工具类和主题令牌。
.module.css@reference "#tailwind";示例:
css
/* component.module.css */
@reference "#tailwind";
.component {
/* 无法用Tailwind工具类实现的复杂CSS */
/* 仍可使用Tailwind工具类和主题令牌 */
}Common Tasks
常见任务
Adding a Component with Variants
添加带变体的组件
- Read for patterns
references/tailwind-variants.md - Check the project's configuration for available tokens
@theme - Use from
tv()for type-safe variantstailwind-variants
Example:
typescript
import { tv } from "tailwind-variants";
const button = tv({
base: "rounded-lg px-4 py-2 font-medium",
variants: {
color: {
primary: "bg-blue-600 text-white",
secondary: "bg-gray-600 text-white",
},
size: {
sm: "text-sm",
md: "text-base",
lg: "text-lg",
},
},
});- 查看了解模式
references/tailwind-variants.md - 查看项目的配置获取可用令牌
@theme - 使用中的
tailwind-variants实现类型安全的变体tv()
示例:
typescript
import { tv } from "tailwind-variants";
const button = tv({
base: "rounded-lg px-4 py-2 font-medium",
variants: {
color: {
primary: "bg-blue-600 text-white",
secondary: "bg-gray-600 text-white",
},
size: {
sm: "text-sm",
md: "text-base",
lg: "text-lg",
},
},
});Debugging Styles
调试样式
- Check for breaking changes
references/tailwind-v4-rules.md - Verify gradient syntax (, not
bg-linear-*)bg-gradient-* - Verify CSS variable syntax (, not
bg-my-color)bg-[--var-my-color] - Check if arbitrary value exists in the project's configuration
@theme
- 查看了解破坏性变更
references/tailwind-v4-rules.md - 验证渐变语法(,而非
bg-linear-*)bg-gradient-* - 验证CSS变量语法(,而非
bg-my-color)bg-[--var-my-color] - 检查任意值是否存在于项目的配置中
@theme
Working with Colors
颜色使用
- Check the project's configuration first to see available colors
@theme - Use semantic color names when available
- Use opacity modifiers for transparency (,
/20, etc.)/50 - Avoid arbitrary colors unless absolutely necessary
Example:
typescript
// ✅ Good: theme token with opacity
<div className="bg-brand/20 text-brand">
// ❌ Avoid: arbitrary hex
<div className="bg-[#4f46e5]/20 text-[#4f46e5]">- 先查看项目的配置了解可用颜色
@theme - 尽可能使用语义化颜色名称
- 使用透明度修饰符设置透明度(、
/20等)/50 - 除非绝对必要,否则避免使用任意颜色
示例:
typescript
// ✅ 推荐写法:带透明度的主题令牌
<div className="bg-brand/20 text-brand">
// ❌ 避免使用:任意十六进制值
<div className="bg-[#4f46e5]/20 text-[#4f46e5]">Adding Animations
添加动画
- Read for available animations
references/tw-animate-css.md - Combine a base class (or
animate-in) with effect classesanimate-out - Note decimal spacing gotcha: use syntax, not
[0.625rem]2.5
Example:
typescript
// Enter: fade + slide up
<div className="fade-in slide-in-from-bottom-4 duration-300 animate-in">
// Exit: fade + slide down
<div className="fade-out slide-out-to-bottom-4 duration-200 animate-out">- 查看了解可用动画
references/tw-animate-css.md - 结合基础类(或
animate-in)与效果类animate-out - 注意小数间距问题:使用语法,而非
[0.625rem]2.5
示例:
typescript
// 进入动画:淡入 + 向上滑入
<div className="fade-in slide-in-from-bottom-4 duration-300 animate-in">
// 退出动画:淡出 + 向下滑出
<div className="fade-out slide-out-to-bottom-4 duration-200 animate-out">Quick Reference Table
快速参考表
| Aspect | Pattern |
|---|---|
| Configuration | CSS-only: |
| Gradients | |
| Opacity | Modifier syntax: |
| Line Height | Modifier syntax: |
| CSS Variables | |
| CSS Modules | |
| Class Merging | |
| Viewport | |
| Component Variants | |
| Animations | |
| V4 Rules | |
| 方面 | 模式 |
|---|---|
| 配置方式 | 纯CSS: |
| 渐变 | |
| 透明度 | 修饰符语法: |
| 行高 | 修饰符语法: |
| CSS变量 | |
| CSS Modules | 顶部添加 |
| 类合并 | 条件类用 |
| 视口高度 | |
| 组件变体 | |
| 动画 | |
| V4规则 | |
Reference Documentation
参考文档
- Tailwind v4 Rules & Best Practices: — Breaking changes, removed/renamed utilities, layout rules, typography, gradients, CSS variables, new v4 features, common pitfalls
references/tailwind-v4-rules.md - tailwind-variants Patterns: — Component variants, slots API, composition, TypeScript integration, responsive variants
references/tailwind-variants.md - tw-animate-css Reference: — Enter/exit animations, slide/fade/zoom utilities, spacing gotchas
references/tw-animate-css.md
- Tailwind v4规则与最佳实践: — 破坏性变更、已移除/重命名的工具类、布局规则、排版、渐变、CSS变量、v4新特性、常见陷阱
references/tailwind-v4-rules.md - tailwind-variants模式: — 组件变体、插槽API、组合、TypeScript集成、响应式变体
references/tailwind-variants.md - tw-animate-css参考: — 进入/退出动画、滑动/淡入/缩放工具类、间距问题
references/tw-animate-css.md