tailwindcss-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Tailwind CSS v4.x Best Practices

Tailwind CSS v4.x 最佳实践

Covers Tailwind CSS v4.0 through v4.2.2 (latest stable as of March 2026). Always check the official docs at https://tailwindcss.com/docs for the latest.
Tailwind CSS is a utility-first CSS framework. Instead of writing custom CSS, you compose designs using utility classes directly in your markup. Tailwind v4 introduced CSS-first configuration with
@theme
variables,
@utility
for custom utilities, and
@custom-variant
for custom variants — replacing the old
tailwind.config.js
approach entirely.
涵盖Tailwind CSS v4.0至v4.2.2版本(截至2026年3月的最新稳定版)。请始终访问官方文档https://tailwindcss.com/docs获取最新内容。
Tailwind CSS是一款优先实用类的CSS框架。无需编写自定义CSS,你可以直接在标记语言中组合实用类来完成设计。Tailwind v4引入了基于CSS的配置方式,使用
@theme
变量、
@utility
定义自定义实用类、
@custom-variant
定义自定义变体——完全取代了旧版的
tailwind.config.js
配置方式。

Critical v4 Migration Gotchas

v4迁移关键注意事项

These are the most common mistakes when working with Tailwind v4. If you're migrating from v3 or using v4 for the first time, read the upgrade guide — but here are the top trip-ups:
v3 (old)v4 (correct)Why it changed
!bg-red-500
bg-red-500!
Important modifier moved from prefix to suffix
bg-opacity-75
bg-red-500/75
Opacity modifiers removed; use slash syntax on the color
shadow
shadow-sm
Shadow scale shifted down one step
shadow-sm
shadow-xs
Shadow scale shifted down one step
rounded
rounded-sm
Border radius scale shifted down one step
rounded-sm
rounded-xs
Border radius scale shifted down one step
ring
ring-3
Default ring width changed from 3px to 1px
outline-none
outline-hidden
Renamed for clarity
flex-shrink-0
shrink-0
Shorter alias is now the only form
flex-grow
grow
Shorter alias is now the only form
overflow-ellipsis
text-ellipsis
Renamed for consistency
blur
blur-sm
Blur scale shifted down one step
@tailwind base/components/utilities
@import "tailwindcss"
Single CSS import replaces three directives
tailwind.config.js
@theme { }
in CSS
CSS-first configuration replaces JS config
darkMode: 'class'
@custom-variant dark (&:where(.dark, .dark *));
Dark mode config moves to CSS
bg-[--var]
bg-(--var)
CSS variable arbitrary values use parentheses
theme(screens.xl)
theme(--breakpoint-xl)
Theme function uses CSS variable names
@layer utilities { }
@utility name { }
Custom utilities use dedicated directive
start-*
/
end-*
inset-s-*
/
inset-e-*
Deprecated in v4.2
这些是使用Tailwind v4时最常见的错误。如果你正从v3迁移或首次使用v4,请阅读升级指南——以下是最容易踩坑的点:
v3(旧版)v4(正确写法)变更原因
!bg-red-500
bg-red-500!
重要修饰符从前缀移至后缀
bg-opacity-75
bg-red-500/75
移除透明度修饰符;使用颜色后的斜杠语法
shadow
shadow-sm
阴影层级整体下移一级
shadow-sm
shadow-xs
阴影层级整体下移一级
rounded
rounded-sm
边框圆角层级整体下移一级
rounded-sm
rounded-xs
边框圆角层级整体下移一级
ring
ring-3
默认环形宽度从3px改为1px
outline-none
outline-hidden
重命名以提高清晰度
flex-shrink-0
shrink-0
仅保留更短的别名写法
flex-grow
grow
仅保留更短的别名写法
overflow-ellipsis
text-ellipsis
重命名以保持一致性
blur
blur-sm
模糊效果层级整体下移一级
@tailwind base/components/utilities
@import "tailwindcss"
单个CSS导入语句替代三个指令
tailwind.config.js
CSS中的
@theme { }
基于CSS的配置替代JS配置
darkMode: 'class'
@custom-variant dark (&:where(.dark, .dark *));
暗色模式配置移至CSS
bg-[--var]
bg-(--var)
CSS变量任意值使用括号
theme(screens.xl)
theme(--breakpoint-xl)
Theme函数使用CSS变量名
@layer utilities { }
@utility name { }
自定义实用类使用专用指令
start-*
/
end-*
inset-s-*
/
inset-e-*
v4.2中已弃用

Core References

核心参考

TopicDescriptionReference
InstallationVite, PostCSS, Webpack, CLI, and CDN setupcore-installation
Utility ClassesUnderstanding Tailwind's utility-first approachcore-utility-classes
Theme VariablesDesign tokens,
@theme
directive, theme variable namespaces
core-theme
Responsive DesignMobile-first breakpoints, responsive variants, container queriescore-responsive
VariantsConditional styling with state, pseudo-class, media query, and pointer variantscore-variants
PreflightTailwind's base styles and how to extend or disable themcore-preflight
Source DetectionHow Tailwind detects classes,
@source
,
@source not
,
@source inline()
core-source-detection
主题描述参考链接
安装Vite、PostCSS、Webpack、CLI和CDN设置core-installation
实用类理解Tailwind的优先实用类方法core-utility-classes
主题变量设计标记、
@theme
指令、主题变量命名空间
core-theme
响应式设计移动优先断点、响应式变体、容器查询core-responsive
变体使用状态、伪类、媒体查询和指针变体实现条件样式core-variants
基础样式Tailwind的基础样式及扩展或禁用方法core-preflight
源检测Tailwind如何检测类、
@source
@source not
@source inline()
core-source-detection

Layout

布局

Display & Flexbox & Grid

显示与Flexbox与Grid

TopicDescriptionReference
Displayflex, grid, block, inline, hidden, sr-only, flow-root, contentslayout-display
Flexboxflex-direction, justify, items, gap, grow, shrink, wrap, orderlayout-flexbox
Gridgrid-cols, grid-rows, gap, place-items, col-span, row-span, subgridlayout-grid
Aspect RatioControlling element aspect ratio for responsive medialayout-aspect-ratio
ColumnsMulti-column layout for magazine-style or masonry layoutslayout-columns
主题描述参考链接
显示flex、grid、block、inline、hidden、sr-only、flow-root、contentslayout-display
Flexboxflex-direction、justify、items、gap、grow、shrink、wrap、orderlayout-flexbox
Gridgrid-cols、grid-rows、gap、place-items、col-span、row-span、subgridlayout-grid
宽高比控制元素宽高比以适配响应式媒体layout-aspect-ratio
多列布局杂志风格或瀑布流布局的多列设置layout-columns

Positioning

定位

TopicDescriptionReference
PositionControlling element positioning with static, relative, absolute, fixed, and stickylayout-position
InsetPlacement of positioned elements with inset, logical inset (
inset-s-*
,
inset-bs-*
), and deprecated
start-*
/
end-*
layout-inset
主题描述参考链接
定位使用static、relative、absolute、fixed和sticky控制元素定位layout-position
内边距偏移定位元素的偏移设置,包括逻辑偏移(
inset-s-*
inset-bs-*
)及已弃用的
start-*
/
end-*
layout-inset

Sizing

尺寸

TopicDescriptionReference
WidthSetting element width with spacing scale, fractions, container sizes, viewport unitslayout-width
HeightSetting element height with spacing scale, fractions, viewport unitslayout-height
Min & Max Sizingmin-width, max-width, min-height, max-height constraintslayout-min-max-sizing
Logical SizingWriting-mode-aware sizing:
inline-*
,
block-*
,
min-inline-*
,
max-block-*
(v4.2)
layout-logical-properties
主题描述参考链接
宽度使用间距比例、分数、容器尺寸、视窗单位设置元素宽度layout-width
高度使用间距比例、分数、视窗单位设置元素高度layout-height
最小与最大尺寸min-width、max-width、min-height、max-height约束layout-min-max-sizing
逻辑尺寸支持书写模式的尺寸:
inline-*
block-*
min-inline-*
max-block-*
(v4.2)
layout-logical-properties

Spacing

间距

TopicDescriptionReference
MarginMargins with spacing scale, negative values, logical properties (
mbs-*
,
mbe-*
)
layout-margin
PaddingPadding with spacing scale, logical properties (
pbs-*
,
pbe-*
)
layout-padding
主题描述参考链接
外边距带间距比例、负值、逻辑属性(
mbs-*
mbe-*
)的外边距
layout-margin
内边距带间距比例、逻辑属性(
pbs-*
pbe-*
)的内边距
layout-padding

Overflow

溢出

TopicDescriptionReference
OverflowControlling how elements handle content that overflowslayout-overflow
主题描述参考链接
溢出控制元素处理溢出内容的方式layout-overflow

Images & Replaced Elements

图片与替换元素

TopicDescriptionReference
Object Fit & PositionControlling how images and video are resized and positionedlayout-object-fit-position
主题描述参考链接
对象适配与定位控制图片和视频的缩放与定位方式layout-object-fit-position

Tables

表格

TopicDescriptionReference
Table Layoutborder-collapse, table-auto, table-fixedlayout-tables
主题描述参考链接
表格布局border-collapse、table-auto、table-fixedlayout-tables

Transforms

变换

TopicDescriptionReference
Transform BaseBase transform utilities, hardware acceleration, custom transform valuestransform-base
TranslateTranslating elements on x, y, z axes with spacing scale and percentagestransform-translate
RotateRotating elements in 2D and 3D spacetransform-rotate
ScaleScaling elements uniformly or on specific axestransform-scale
SkewSkewing elements on x and y axestransform-skew
主题描述参考链接
变换基础基础变换实用类、硬件加速、自定义变换值transform-base
平移使用间距比例和百分比在x、y、z轴平移元素transform-translate
旋转在2D和3D空间旋转元素transform-rotate
缩放均匀或沿特定轴缩放元素transform-scale
倾斜在x和y轴倾斜元素transform-skew

Typography

排版

TopicDescriptionReference
Font & TextFont size, weight, color, line-height, letter-spacing, decoration, truncate,
wrap-break-word
,
wrap-anywhere
typography-font-text
Text AlignControlling text alignment with left, center, right, justifytypography-text-align
List Stylelist-style-type, list-style-position for bullets and markerstypography-list-style
主题描述参考链接
字体与文本字体大小、字重、颜色、行高、字母间距、装饰、截断、
wrap-break-word
wrap-anywhere
typography-font-text
文本对齐使用左对齐、居中、右对齐、两端对齐控制文本对齐方式typography-text-align
列表样式项目符号和标记的list-style-type、list-style-positiontypography-list-style

Visual

视觉效果

TopicDescriptionReference
BackgroundBackground color, gradient, image, size, positionvisual-background
BorderBorder width, color, radius, divide, ring, block border utilities (
border-bs-*
,
border-be-*
)
visual-border
EffectsBox shadow, opacity, mix-blend, backdrop-blur, filter, colored drop shadowsvisual-effects
SVGfill, stroke, stroke-width for SVG and icon stylingvisual-svg
Text ShadowText shadow sizes, colors, and opacity modifiers (v4.1)effects-text-shadow
MaskComposable mask utilities with gradient and radial masks (v4.1)effects-mask
主题描述参考链接
背景背景颜色、渐变、图片、尺寸、位置visual-background
边框边框宽度、颜色、圆角、分隔线、环形、块级边框实用类(
border-bs-*
border-be-*
visual-border
特效盒阴影、透明度、混合模式、背景模糊、滤镜、彩色投影visual-effects
SVGSVG和图标样式的fill、stroke、stroke-widthvisual-svg
文本阴影文本阴影尺寸、颜色和透明度修饰符(v4.1)effects-text-shadow
遮罩可组合的遮罩实用类,包括渐变和径向遮罩(v4.1)effects-mask

Effects & Interactivity

特效与交互

TopicDescriptionReference
Transition & AnimationCSS transitions, animation keyframes, reduced motioneffects-transition-animation
Visibility & InteractivityVisibility, cursor, pointer-events, user-select, z-indexeffects-visibility-interactivity
Form Controlsaccent-color, appearance, caret-color, resizeeffects-form-controls
Scroll Snapscroll-snap-type, scroll-snap-align for carouselseffects-scroll-snap
主题描述参考链接
过渡与动画CSS过渡、动画关键帧、减少动画effects-transition-animation
可见性与交互可见性、光标、指针事件、用户选择、z-indexeffects-visibility-interactivity
表单控件accent-color、外观、光标颜色、调整大小effects-form-controls
滚动捕捉轮播图的scroll-snap-type、scroll-snap-aligneffects-scroll-snap

Features

功能特性

Dark Mode

暗色模式

TopicDescriptionReference
Dark ModeDark mode with
dark:
variant,
@custom-variant
, class and data-attribute strategies
features-dark-mode
主题描述参考链接
暗色模式
dark:
变体、
@custom-variant
、类和数据属性策略的暗色模式
features-dark-mode

Migration

迁移

TopicDescriptionReference
Upgrade GuideMigrating from v3 to v4, all renamed/removed utilities, scale shifts, config migrationfeatures-upgrade
主题描述参考链接
升级指南从v3迁移到v4、所有重命名/移除的实用类、层级变更、配置迁移features-upgrade

Customization

自定义

TopicDescriptionReference
Custom StylesAdding custom styles, utilities with
@utility
, variants with
@custom-variant
, arbitrary values
features-custom-styles
Functions & DirectivesTailwind's CSS directives (
@theme
,
@utility
,
@custom-variant
,
@source
) and functions
features-functions-directives
Content DetectionHow Tailwind detects classes,
@source
configuration, safelisting with
@source inline()
features-content-detection
主题描述参考链接
自定义样式添加自定义样式、使用
@utility
的实用类、使用
@custom-variant
的变体、任意值
features-custom-styles
函数与指令Tailwind的CSS指令(
@theme
@utility
@custom-variant
@source
)和函数
features-functions-directives
内容检测Tailwind如何检测类、
@source
配置、使用
@source inline()
添加安全列表
features-content-detection

Best Practices

最佳实践

TopicDescriptionReference
Utility PatternsManaging duplication, conflicts, important modifier, when to use componentsbest-practices-utility-patterns
主题描述参考链接
实用类模式管理重复代码、冲突、重要修饰符、何时使用组件best-practices-utility-patterns

Key Recommendations

关键建议

  • Use utility classes directly in markup — compose designs by combining utilities
  • Customize with
    @theme
    directive
    — define design tokens as CSS variables, not in JS config
  • Mobile-first responsive design — unprefixed utilities for mobile, prefixed for breakpoints
  • Use complete class names — never construct classes dynamically with string interpolation
  • Leverage variants — stack variants for complex conditional styling (
    dark:md:hover:bg-blue-600
    )
  • Prefer CSS-first configuration — use
    @theme
    ,
    @utility
    , and
    @custom-variant
    over JavaScript configs
  • Use oklch for custom colors — Tailwind v4 defaults to oklch; prefer it for perceptual uniformity
  • Use rem for custom breakpoints — e.g.,
    --breakpoint-3xl: 90rem
    not
    1440px
  • Know the scale shifts — shadow, rounded, and blur all shifted down one step in v4
  • Use
    @custom-variant
    (not
    @variant
    ) — for defining custom variants like class-based dark mode
  • 直接在标记中使用实用类——通过组合实用类来构建设计
  • 使用
    @theme
    指令自定义
    ——将设计标记定义为CSS变量,而非JS配置
  • 移动端优先的响应式设计——无前缀的实用类用于移动端,带前缀的用于断点
  • 使用完整类名——永远不要通过字符串拼接动态构建类名
  • 利用变体——堆叠变体实现复杂的条件样式(如
    dark:md:hover:bg-blue-600
  • 优先使用基于CSS的配置——使用
    @theme
    @utility
    @custom-variant
    而非JavaScript配置
  • 使用oklch定义自定义颜色——Tailwind v4默认使用oklch;优先选择以保证感知一致性
  • 使用rem定义自定义断点——例如
    --breakpoint-3xl: 90rem
    而非
    1440px
  • 了解层级变更——v4中阴影、圆角和模糊效果的层级均下移一级
  • 使用
    @custom-variant
    (而非
    @variant
    )——用于定义类基暗色模式等自定义变体