tailwind-css
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTailwind CSS - Utility-First Framework
Tailwind CSS - 实用优先框架
A comprehensive skill for mastering Tailwind CSS, the utility-first CSS framework for rapidly building custom user interfaces. This skill covers core concepts, responsive design patterns, component extraction, dark mode implementation, theme customization, and production optimization.
这是一套全面掌握Tailwind CSS的指南,Tailwind CSS是一款实用优先的CSS框架,可快速构建自定义用户界面。本指南涵盖核心概念、响应式设计模式、组件提取、深色模式实现、主题自定义以及生产环境优化等内容。
When to Use This Skill
何时使用本指南
Use this skill when:
- Building modern web applications with utility-first CSS approach
- Creating responsive designs that work across all device sizes
- Implementing dark mode and theme switching in applications
- Developing reusable component libraries with consistent styling
- Optimizing CSS performance for production deployments
- Customizing design systems with brand-specific tokens
- Building accessible, mobile-first user interfaces
- Integrating with frameworks like React, Vue, Svelte, or Next.js
- Prototyping and iterating on UI designs rapidly
- Maintaining design consistency across large codebases
在以下场景使用本指南:
- 使用实用优先的CSS方法构建现代Web应用
- 创建适配所有设备尺寸的响应式设计
- 在应用中实现深色模式和主题切换
- 开发样式一致的可复用组件库
- 优化生产部署的CSS性能
- 使用品牌专属的设计令牌自定义设计系统
- 构建可访问、移动优先的用户界面
- 与React、Vue、Svelte或Next.js等框架集成
- 快速原型制作和迭代UI设计
- 在大型代码库中维持设计一致性
Core Concepts
核心概念
Utility-First Philosophy
实用优先理念
Tailwind CSS takes a different approach from traditional CSS frameworks:
- Utility Classes Over Components: Instead of pre-built components, use single-purpose utility classes
- Compose in HTML: Build complex designs by composing utilities directly in your markup
- No Context Switching: Stay in your HTML/JSX without jumping to CSS files
- Design System Built-In: Consistent spacing, colors, and typography out of the box
- Responsive by Default: Every utility has responsive variants built-in
- JIT Compilation: Just-in-Time mode generates only the CSS you actually use
Tailwind CSS采用与传统CSS框架不同的方法:
- 工具类优先而非组件:使用单一用途的工具类而非预构建组件
- 在HTML中组合:直接在标记中组合工具类来构建复杂设计
- 无需上下文切换:无需跳转到CSS文件,始终在HTML/JSX中操作
- 内置设计系统:开箱即用的一致间距、颜色和排版
- 默认支持响应式:每个工具类都内置响应式变体
- JIT编译:即时编译模式仅生成实际使用的CSS
Key Principles
关键原则
- Single Responsibility: Each class does one thing well
- Composability: Combine utilities to create complex designs
- Constraints: Design system constraints lead to better, more consistent UIs
- Flexibility: Arbitrary values for one-off customizations when needed
- Performance: Minimal CSS output through intelligent purging
- 单一职责:每个类只专注完成一件事
- 可组合性:组合工具类来创建复杂设计
- 约束性:设计系统的约束能带来更优质、一致的UI
- 灵活性:需要时可使用任意值进行一次性自定义
- 性能:通过智能清理生成最小化的CSS输出
Core Utilities Reference
核心工具类参考
Layout Utilities
布局工具类
Display
显示方式
html
<!-- Block and inline -->
<div class="block">Block element</div>
<span class="inline">Inline element</span>
<div class="inline-block">Inline-block</div>
<!-- Flexbox -->
<div class="flex items-center justify-between">
<div>Left</div>
<div>Right</div>
</div>
<!-- Grid -->
<div class="grid grid-cols-3 gap-4">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<!-- Hidden -->
<div class="hidden md:block">Visible on medium screens and up</div>html
<!-- 块级和内联元素 -->
<div class="block">块级元素</div>
<span class="inline">内联元素</span>
<div class="inline-block">内联块级元素</div>
<!-- Flexbox布局 -->
<div class="flex items-center justify-between">
<div>左侧</div>
<div>右侧</div>
</div>
<!-- Grid布局 -->
<div class="grid grid-cols-3 gap-4">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<!-- 隐藏元素 -->
<div class="hidden md:block">中等屏幕及以上可见</div>Positioning
定位
html
<!-- Static, relative, absolute, fixed, sticky -->
<div class="relative">
<div class="absolute top-0 right-0">Top-right corner</div>
</div>
<div class="fixed bottom-4 right-4">Fixed bottom-right</div>
<div class="sticky top-0">Sticky header</div>html
<!-- 静态、相对、绝对、固定、粘性定位 -->
<div class="relative">
<div class="absolute top-0 right-0">右上角</div>
</div>
<div class="fixed bottom-4 right-4">固定在右下角</div>
<div class="sticky top-0">粘性头部</div>Sizing
尺寸
html
<!-- Width and height -->
<div class="w-full h-screen">Full width, viewport height</div>
<div class="w-1/2 h-64">Half width, 16rem height</div>
<div class="w-[750px] h-[500px]">Arbitrary values</div>
<!-- Min/max -->
<div class="min-w-0 max-w-md">Constrained width</div>
<div class="min-h-screen max-h-full">Constrained height</div>html
<!-- 宽度和高度 -->
<div class="w-full h-screen">全屏宽度,视口高度</div>
<div class="w-1/2 h-64">半宽,16rem高度</div>
<div class="w-[750px] h-[500px]">任意值</div>
<!-- 最小/最大尺寸 -->
<div class="min-w-0 max-w-md">受限宽度</div>
<div class="min-h-screen max-h-full">受限高度</div>Spacing Utilities
间距工具类
Padding and Margin
内边距和外边距
html
<!-- All sides -->
<div class="p-4 m-2">Padding 1rem, margin 0.5rem</div>
<!-- Individual sides -->
<div class="pt-8 pb-4 pl-6 pr-2">Individual padding</div>
<div class="mt-4 mb-8 ml-auto mr-auto">Individual margin</div>
<!-- Logical properties -->
<div class="px-4 py-2">Horizontal and vertical</div>
<div class="ps-4 pe-2">Inline start/end (RTL-aware)</div>
<!-- Negative margins -->
<div class="-mt-4 -ml-2">Negative margins for overlap</div>
<!-- Space between -->
<div class="flex space-x-4">Horizontal spacing between children</div>
<div class="flex flex-col space-y-2">Vertical spacing between children</div>html
<!-- 四边统一 -->
<div class="p-4 m-2">内边距1rem,外边距0.5rem</div>
<!-- 单独边设置 -->
<div class="pt-8 pb-4 pl-6 pr-2">单独设置内边距</div>
<div class="mt-4 mb-8 ml-auto mr-auto">单独设置外边距</div>
<!-- 逻辑属性 -->
<div class="px-4 py-2">水平和垂直方向</div>
<div class="ps-4 pe-2">内联开始/结束(支持RTL)</div>
<!-- 负外边距 -->
<div class="-mt-4 -ml-2">负外边距用于重叠效果</div>
<!-- 子元素间距 -->
<div class="flex space-x-4">子元素水平间距</div>
<div class="flex flex-col space-y-2">子元素垂直间距</div>Typography Utilities
排版工具类
Font Family, Size, and Weight
字体族、字号和字重
html
<!-- Font families -->
<p class="font-sans">Sans-serif font</p>
<p class="font-serif">Serif font</p>
<p class="font-mono">Monospace font</p>
<!-- Font sizes -->
<p class="text-xs">Extra small (0.75rem)</p>
<p class="text-sm">Small (0.875rem)</p>
<p class="text-base">Base (1rem)</p>
<p class="text-lg">Large (1.125rem)</p>
<p class="text-xl">Extra large (1.25rem)</p>
<h1 class="text-4xl">4XL heading (2.25rem)</h1>
<!-- Font weights -->
<p class="font-light">Light (300)</p>
<p class="font-normal">Normal (400)</p>
<p class="font-medium">Medium (500)</p>
<p class="font-semibold">Semibold (600)</p>
<p class="font-bold">Bold (700)</p>html
<!-- 字体族 -->
<p class="font-sans">无衬线字体</p>
<p class="font-serif">衬线字体</p>
<p class="font-mono">等宽字体</p>
<!-- 字号 -->
<p class="text-xs">超小(0.75rem)</p>
<p class="text-sm">小(0.875rem)</p>
<p class="text-base">基础(1rem)</p>
<p class="text-lg">大(1.125rem)</p>
<p class="text-xl">超大(1.25rem)</p>
<h1 class="text-4xl">4XL标题(2.25rem)</h1>
<!-- 字重 -->
<p class="font-light">轻量(300)</p>
<p class="font-normal">常规(400)</p>
<p class="font-medium">中等(500)</p>
<p class="font-semibold">半粗体(600)</p>
<p class="font-bold">粗体(700)</p>Text Styling
文本样式
html
<!-- Text alignment -->
<p class="text-left">Left aligned</p>
<p class="text-center">Center aligned</p>
<p class="text-right">Right aligned</p>
<!-- Text color -->
<p class="text-gray-900">Dark gray text</p>
<p class="text-blue-600">Blue text</p>
<p class="text-red-500/75">Red text with 75% opacity</p>
<!-- Text decoration -->
<p class="underline">Underlined text</p>
<p class="line-through">Strikethrough text</p>
<a class="no-underline hover:underline">Hover underline</a>
<!-- Text transform -->
<p class="uppercase">UPPERCASE TEXT</p>
<p class="lowercase">lowercase text</p>
<p class="capitalize">Capitalize Each Word</p>
<!-- Line height and letter spacing -->
<p class="leading-tight">Tight line height</p>
<p class="leading-relaxed">Relaxed line height</p>
<p class="tracking-wide">Wide letter spacing</p>html
<!-- 文本对齐 -->
<p class="text-left">左对齐</p>
<p class="text-center">居中对齐</p>
<p class="text-right">右对齐</p>
<!-- 文本颜色 -->
<p class="text-gray-900">深灰色文本</p>
<p class="text-blue-600">蓝色文本</p>
<p class="text-red-500/75">75%不透明度的红色文本</p>
<!-- 文本装饰 -->
<p class="underline">下划线文本</p>
<p class="line-through">删除线文本</p>
<a class="no-underline hover:underline">hover时显示下划线</a>
<!-- 文本转换 -->
<p class="uppercase">全大写文本</p>
<p class="lowercase">全小写文本</p>
<p class="capitalize">首字母大写</p>
<!-- 行高和字间距 -->
<p class="leading-tight">紧凑行高</p>
<p class="leading-relaxed">宽松行高</p>
<p class="tracking-wide">宽字间距</p>Color Utilities
颜色工具类
Background Colors
背景色
html
<!-- Solid backgrounds -->
<div class="bg-white">White background</div>
<div class="bg-gray-100">Light gray background</div>
<div class="bg-blue-500">Blue background</div>
<div class="bg-red-600/50">Red background at 50% opacity</div>
<!-- Gradients -->
<div class="bg-gradient-to-r from-purple-500 to-pink-500">
Purple to pink gradient
</div>
<div class="bg-gradient-to-br from-blue-400 via-purple-500 to-pink-600">
Three-color gradient
</div>html
<!-- 纯色背景 -->
<div class="bg-white">白色背景</div>
<div class="bg-gray-100">浅灰色背景</div>
<div class="bg-blue-500">蓝色背景</div>
<div class="bg-red-600/50">50%不透明度的红色背景</div>
<!-- 渐变背景 -->
<div class="bg-gradient-to-r from-purple-500 to-pink-500">
紫色到粉色的渐变
</div>
<div class="bg-gradient-to-br from-blue-400 via-purple-500 to-pink-600">
三色渐变
</div>Text and Border Colors
文本和边框颜色
html
<!-- Text colors -->
<p class="text-gray-900 dark:text-white">Adaptive text color</p>
<p class="text-blue-600 hover:text-blue-800">Interactive text color</p>
<!-- Border colors -->
<div class="border border-gray-300">Gray border</div>
<div class="border-2 border-blue-500">Thick blue border</div>
<div class="divide-y divide-gray-200">Divided children</div>html
<!-- 文本颜色 -->
<p class="text-gray-900 dark:text-white">自适应文本颜色</p>
<p class="text-blue-600 hover:text-blue-800">交互式文本颜色</p>
<!-- 边框颜色 -->
<div class="border border-gray-300">灰色边框</div>
<div class="border-2 border-blue-500">粗蓝色边框</div>
<div class="divide-y divide-gray-200">子元素间分隔线</div>Border and Rounding Utilities
边框和圆角工具类
html
<!-- Border width -->
<div class="border">1px border</div>
<div class="border-2">2px border</div>
<div class="border-t-4">4px top border only</div>
<!-- Border radius -->
<div class="rounded">0.25rem radius</div>
<div class="rounded-lg">0.5rem radius</div>
<div class="rounded-full">Full circle/pill</div>
<div class="rounded-t-lg">Round top only</div>
<!-- Border style -->
<div class="border-solid">Solid border</div>
<div class="border-dashed">Dashed border</div>
<div class="border-dotted">Dotted border</div>html
<!-- 边框宽度 -->
<div class="border">1px边框</div>
<div class="border-2">2px边框</div>
<div class="border-t-4">仅顶部4px边框</div>
<!-- 边框圆角 -->
<div class="rounded">0.25rem圆角</div>
<div class="rounded-lg">0.5rem圆角</div>
<div class="rounded-full">全圆角(圆形/胶囊形)</div>
<div class="rounded-t-lg">仅顶部圆角</div>
<!-- 边框样式 -->
<div class="border-solid">实线边框</div>
<div class="border-dashed">虚线边框</div>
<div class="border-dotted">点线边框</div>Shadow and Effects
阴影和效果
html
<!-- Box shadows -->
<div class="shadow-sm">Small shadow</div>
<div class="shadow-md">Medium shadow</div>
<div class="shadow-lg">Large shadow</div>
<div class="shadow-xl">Extra large shadow</div>
<div class="shadow-none hover:shadow-lg">Interactive shadow</div>
<!-- Text shadow -->
<h1 class="text-shadow-lg">Large text shadow</h1>
<p class="text-shadow-sm text-shadow-gray-300">Colored text shadow</p>
<!-- Opacity -->
<div class="opacity-50">50% opacity</div>
<div class="opacity-0 hover:opacity-100">Fade in on hover</div>html
<!-- 盒子阴影 -->
<div class="shadow-sm">小阴影</div>
<div class="shadow-md">中等阴影</div>
<div class="shadow-lg">大阴影</div>
<div class="shadow-xl">超大阴影</div>
<div class="shadow-none hover:shadow-lg">交互式阴影</div>
<!-- 文本阴影 -->
<h1 class="text-shadow-lg">大文本阴影</h1>
<p class="text-shadow-sm text-shadow-gray-300">彩色文本阴影</p>
<!-- 不透明度 -->
<div class="opacity-50">50%不透明度</div>
<div class="opacity-0 hover:opacity-100">hover时渐显</div>Responsive Design
响应式设计
Breakpoint System
断点系统
Tailwind uses a mobile-first breakpoint system:
css
/* Breakpoint reference */
sm: 640px /* @media (min-width: 640px) */
md: 768px /* @media (min-width: 768px) */
lg: 1024px /* @media (min-width: 1024px) */
xl: 1280px /* @media (min-width: 1280px) */
2xl: 1536px /* @media (min-width: 1536px) */Tailwind采用移动优先的断点系统:
css
/* 断点参考 */
sm: 640px /* @media (min-width: 640px) */
md: 768px /* @media (min-width: 768px) */
lg: 1024px /* @media (min-width: 1024px) */
xl: 1280px /* @media (min-width: 1280px) */
2xl: 1536px /* @media (min-width: 1536px) */Responsive Utilities
响应式工具类
html
<!-- Mobile-first approach -->
<div class="w-full md:w-1/2 lg:w-1/3">
Full width on mobile, half on tablet, third on desktop
</div>
<!-- Responsive flexbox -->
<div class="flex flex-col md:flex-row gap-4">
Vertical on mobile, horizontal on tablet+
</div>
<!-- Responsive grid -->
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
1 column mobile, 2 tablet, 4 desktop
</div>
<!-- Responsive text -->
<h1 class="text-2xl md:text-4xl lg:text-6xl">
Scales with screen size
</h1>
<!-- Show/hide at breakpoints -->
<div class="block md:hidden">Mobile only</div>
<div class="hidden md:block">Desktop only</div>
<div class="hidden md:block lg:hidden">Tablet only</div>html
<!-- 移动优先方法 -->
<div class="w-full md:w-1/2 lg:w-1/3">
移动端全屏宽度,平板端半宽,桌面端1/3宽
</div>
<!-- 响应式Flexbox -->
<div class="flex flex-col md:flex-row gap-4">
移动端垂直排列,平板及以上水平排列
</div>
<!-- 响应式Grid -->
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
移动端1列,平板2列,桌面4列
</div>
<!-- 响应式文本 -->
<h1 class="text-2xl md:text-4xl lg:text-6xl">
随屏幕尺寸缩放
</h1>
<!-- 断点处显示/隐藏 -->
<div class="block md:hidden">仅移动端可见</div>
<div class="hidden md:block">仅桌面端可见</div>
<div class="hidden md:block lg:hidden">仅平板端可见</div>Custom Breakpoints
自定义断点
css
/* app.css */
@import "tailwindcss";
@theme {
--breakpoint-xs: 30rem; /* 480px */
--breakpoint-3xl: 120rem; /* 1920px */
}html
<!-- Using custom breakpoints -->
<div class="grid xs:grid-cols-2 3xl:grid-cols-6">
Uses custom xs and 3xl breakpoints
</div>css
/* app.css */
@import "tailwindcss";
@theme {
--breakpoint-xs: 30rem; /* 480px */
--breakpoint-3xl: 120rem; /* 1920px */
}html
<!-- 使用自定义断点 -->
<div class="grid xs:grid-cols-2 3xl:grid-cols-6">
使用自定义xs和3xl断点
</div>Targeting Breakpoint Ranges
断点范围定位
html
<!-- Active only between md and xl -->
<div class="md:max-xl:flex">
Flex layout only on tablets
</div>
<!-- Max-width utilities -->
<div class="flex max-md:hidden">
Hidden below medium breakpoint
</div>html
<!-- 仅在md和xl之间生效 -->
<div class="md:max-xl:flex">
仅平板端使用Flex布局
</div>
<!-- 最大宽度工具类 -->
<div class="flex max-md:hidden">
中等断点以下隐藏
</div>Container Queries
容器查询
html
<!-- Container-based responsive design -->
<div class="@container">
<div class="@lg:grid-cols-3 grid grid-cols-1">
Responds to container size, not viewport
</div>
</div>
<!-- Arbitrary container queries -->
<div class="@container">
<div class="flex flex-col @min-[475px]:flex-row">
Custom container breakpoint
</div>
</div>
<!-- Using container query units -->
<div class="@container">
<div class="w-[50cqw]">
50% of container width
</div>
</div>html
<!-- 基于容器的响应式设计 -->
<div class="@container">
<div class="@lg:grid-cols-3 grid grid-cols-1">
响应容器尺寸而非视口尺寸
</div>
</div>
<!-- 任意容器查询 -->
<div class="@container">
<div class="flex flex-col @min-[475px]:flex-row">
自定义容器断点
</div>
</div>
<!-- 使用容器查询单位 -->
<div class="@container">
<div class="w-[50cqw]">
容器宽度的50%
</div>
</div>Dark Mode Implementation
深色模式实现
Automatic Dark Mode (Media Query)
自动深色模式(媒体查询)
Default behavior based on system preference:
html
<!-- Automatically adapts to system preference -->
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
<div class="bg-gray-100 dark:bg-gray-800 p-6 rounded-lg">
<h3 class="text-gray-900 dark:text-white font-semibold">
Card Title
</h3>
<p class="text-gray-500 dark:text-gray-400">
Content automatically adapts to color scheme preference
</p>
</div>
</div>基于系统偏好的默认行为:
html
<!-- 自动适配系统偏好 -->
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
<div class="bg-gray-100 dark:bg-gray-800 p-6 rounded-lg">
<h3 class="text-gray-900 dark:text-white font-semibold">
卡片标题
</h3>
<p class="text-gray-500 dark:text-gray-400">
内容自动适配配色方案偏好
</p>
</div>
</div>Manual Dark Mode (Class-Based)
手动深色模式(基于类)
Configure custom variant for manual control:
css
/* app.css */
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));html
<!-- Toggle dark mode with class -->
<html class="dark">
<body>
<div class="bg-white dark:bg-black">
Controlled by .dark class on ancestor
</div>
</body>
</html>配置自定义变体以实现手动控制:
css
/* app.css */
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));html
<!-- 通过类切换深色模式 -->
<html class="dark">
<body>
<div class="bg-white dark:bg-black">
由祖先元素的.dark类控制
</div>
</body>
</html>Dark Mode Toggle Logic
深色模式切换逻辑
javascript
// Dark mode toggle with localStorage persistence
// Add inline in <head> to avoid FOUC (Flash of Unstyled Content)
document.documentElement.classList.toggle(
"dark",
localStorage.theme === "dark" ||
(!("theme" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches)
);
// User explicitly chooses light mode
function setLightMode() {
localStorage.theme = "light";
document.documentElement.classList.remove("dark");
}
// User explicitly chooses dark mode
function setDarkMode() {
localStorage.theme = "dark";
document.documentElement.classList.add("dark");
}
// User chooses to respect OS preference
function setSystemMode() {
localStorage.removeItem("theme");
document.documentElement.classList.toggle(
"dark",
window.matchMedia("(prefers-color-scheme: dark)").matches
);
}javascript
// 带有localStorage持久化的深色模式切换
// 内联添加到<head>中以避免FOUC(无样式内容闪烁)
document.documentElement.classList.toggle(
"dark",
localStorage.theme === "dark" ||
(!("theme" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches)
);
// 用户明确选择浅色模式
function setLightMode() {
localStorage.theme = "light";
document.documentElement.classList.remove("dark");
}
// 用户明确选择深色模式
function setDarkMode() {
localStorage.theme = "dark";
document.documentElement.classList.add("dark");
}
// 用户选择跟随系统偏好
function setSystemMode() {
localStorage.removeItem("theme");
document.documentElement.classList.toggle(
"dark",
window.matchMedia("(prefers-color-scheme: dark)").matches
);
}Data Attribute Dark Mode
数据属性深色模式
Alternative approach using data attributes:
css
/* app.css */
@import "tailwindcss";
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));html
<html data-theme="dark">
<body>
<div class="bg-white dark:bg-black">
Uses data-theme attribute
</div>
</body>
</html>使用数据属性的替代方案:
css
/* app.css */
@import "tailwindcss";
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));html
<html data-theme="dark">
<body>
<div class="bg-white dark:bg-black">
使用data-theme属性
</div>
</body>
</html>State Variants
状态变体
Interactive States
交互状态
html
<!-- Hover, focus, active states -->
<button class="
bg-blue-500
hover:bg-blue-600
focus:bg-blue-700
active:bg-blue-800
focus:outline-2
focus:outline-offset-2
focus:outline-blue-500
">
Interactive button
</button>
<!-- Disabled state -->
<button class="
bg-blue-500
disabled:opacity-50
disabled:cursor-not-allowed
" disabled>
Disabled button
</button>
<!-- Focus within -->
<div class="border-2 border-transparent focus-within:border-blue-500">
<input class="outline-none" placeholder="Focus container changes" />
</div>html
<!-- 悬停、聚焦、激活状态 -->
<button class="
bg-blue-500
hover:bg-blue-600
focus:bg-blue-700
active:bg-blue-800
focus:outline-2
focus:outline-offset-2
focus:outline-blue-500
">
交互式按钮
</button>
<!-- 禁用状态 -->
<button class="
bg-blue-500
disabled:opacity-50
disabled:cursor-not-allowed
" disabled>
禁用按钮
</button>
<!-- 内部聚焦 -->
<div class="border-2 border-transparent focus-within:border-blue-500">
<input class="outline-none" placeholder="聚焦容器时变化" />
</div>Form States
表单状态
html
<!-- Input states -->
<input class="
border
border-gray-300
focus:border-blue-500
focus:ring-2
focus:ring-blue-200
invalid:border-red-500
placeholder:text-gray-400
" />
<!-- Checkbox and radio -->
<input type="checkbox" class="
checked:bg-blue-500
indeterminate:bg-gray-500
" />
<!-- File input -->
<input type="file" class="
file:mr-4
file:rounded-full
file:border-0
file:bg-violet-50
file:px-4
file:py-2
file:text-sm
file:font-semibold
hover:file:bg-violet-100
" />html
<!-- 输入框状态 -->
<input class="
border
border-gray-300
focus:border-blue-500
focus:ring-2
focus:ring-blue-200
invalid:border-red-500
placeholder:text-gray-400
" />
<!-- 复选框和单选框 -->
<input type="checkbox" class="
checked:bg-blue-500
indeterminate:bg-gray-500
" />
<!-- 文件输入框 -->
<input type="file" class="
file:mr-4
file:rounded-full
file:border-0
file:bg-violet-50
file:px-4
file:py-2
file:text-sm
file:font-semibold
hover:file:bg-violet-100
" />Pseudo-Classes and Pseudo-Elements
伪类和伪元素
html
<!-- First, last, odd, even -->
<ul>
<li class="first:font-bold">First item is bold</li>
<li class="even:bg-gray-100">Even items have background</li>
<li class="last:border-b-0">Last item has no border</li>
</ul>
<!-- Before and after -->
<div class="
before:content-['→']
before:mr-2
after:content-['←']
after:ml-2
">
Content with decorations
</div>
<!-- Group hover -->
<div class="group">
<img class="group-hover:opacity-75" src="..." />
<p class="group-hover:text-blue-600">Hover parent to affect children</p>
</div>
<!-- Peer state -->
<input type="checkbox" class="peer" id="toggle" />
<label class="peer-checked:text-blue-600" for="toggle">
Changes when checkbox is checked
</label>html
<!-- 第一个、最后一个、奇数、偶数项 -->
<ul>
<li class="first:font-bold">第一项为粗体</li>
<li class="even:bg-gray-100">偶数项有背景</li>
<li class="last:border-b-0">最后一项无底部边框</li>
</ul>
<!-- 前置和后置内容 -->
<div class="
before:content-['→']
before:mr-2
after:content-['←']
after:ml-2
">
带装饰的内容
</div>
<!-- 组悬停 -->
<div class="group">
<img class="group-hover:opacity-75" src="..." />
<p class="group-hover:text-blue-600">悬停父元素影响子元素</p>
</div>
<!-- 同伴状态 -->
<input type="checkbox" class="peer" id="toggle" />
<label class="peer-checked:text-blue-600" for="toggle">
复选框选中时变化
</label>Media Query Variants
媒体查询变体
html
<!-- Motion preferences -->
<button class="
transition
hover:-translate-y-1
motion-reduce:transition-none
motion-reduce:hover:translate-y-0
">
Respects user motion preference
</button>
<!-- Contrast preferences -->
<label>
<input class="contrast-more:border-gray-400" />
<p class="opacity-75 contrast-more:opacity-100">
Adjusts for contrast needs
</p>
</label>
<!-- Print styles -->
<article class="print:hidden">Not shown when printing</article>
<div class="hidden print:block">Only visible in print</div>
<!-- Orientation -->
<div class="portrait:hidden">Hidden in portrait mode</div>
<div class="landscape:grid-cols-2">Adapts to orientation</div>html
<!-- 动画偏好 -->
<button class="
transition
hover:-translate-y-1
motion-reduce:transition-none
motion-reduce:hover:translate-y-0
">
尊重用户动画偏好
</button>
<!-- 对比度偏好 -->
<label>
<input class="contrast-more:border-gray-400" />
<p class="opacity-75 contrast-more:opacity-100">
适配对比度需求
</p>
</label>
<!-- 打印样式 -->
<article class="print:hidden">打印时隐藏</article>
<div class="hidden print:block">仅打印可见</div>
<!-- 屏幕方向 -->
<div class="portrait:hidden">竖屏时隐藏</div>
<div class="landscape:grid-cols-2">适配屏幕方向</div>Component Extraction Patterns
组件提取模式
When to Extract Components
何时提取组件
Extract components when:
- Repeated Patterns: Same utility combinations used multiple times
- Semantic Meaning: Pattern represents a specific UI element (button, card)
- Team Communication: Need to share consistent components
- Maintenance: Changes should propagate to all instances
在以下情况提取组件:
- 重复模式:相同的工具类组合被多次使用
- 语义含义:模式代表特定的UI元素(按钮、卡片)
- 团队协作:需要共享一致的组件
- 维护性:修改应同步到所有实例
Framework Component Extraction
框架组件提取
React Components
React组件
jsx
// Button.jsx - Reusable component with variants
export function Button({ size = 'md', variant = 'primary', children, ...props }) {
const baseStyles = "font-bold rounded transition focus:outline-2 focus:outline-offset-2";
const sizeStyles = {
sm: "px-3 py-1.5 text-sm",
md: "px-4 py-2 text-base",
lg: "px-5 py-3 text-lg"
};
const variantStyles = {
primary: "bg-blue-500 text-white hover:bg-blue-600 focus:outline-blue-500",
secondary: "bg-gray-200 text-gray-900 hover:bg-gray-300 focus:outline-gray-500",
danger: "bg-red-500 text-white hover:bg-red-600 focus:outline-red-500"
};
return (
<button
className={`${baseStyles} ${sizeStyles[size]} ${variantStyles[variant]}`}
{...props}
>
{children}
</button>
);
}
// Usage
<Button size="lg" variant="primary">Save Changes</Button>
<Button size="sm" variant="danger">Delete</Button>jsx
// Button.jsx - 带变体的可复用组件
export function Button({ size = 'md', variant = 'primary', children, ...props }) {
const baseStyles = "font-bold rounded transition focus:outline-2 focus:outline-offset-2";
const sizeStyles = {
sm: "px-3 py-1.5 text-sm",
md: "px-4 py-2 text-base",
lg: "px-5 py-3 text-lg"
};
const variantStyles = {
primary: "bg-blue-500 text-white hover:bg-blue-600 focus:outline-blue-500",
secondary: "bg-gray-200 text-gray-900 hover:bg-gray-300 focus:outline-gray-500",
danger: "bg-red-500 text-white hover:bg-red-600 focus:outline-red-500"
};
return (
<button
className={`${baseStyles} ${sizeStyles[size]} ${variantStyles[variant]}`}
{...props}
>
{children}
</button>
);
}
// 使用示例
<Button size="lg" variant="primary">保存更改</Button>
<Button size="sm" variant="danger">删除</Button>Vue Components
Vue组件
vue
<!-- Card.vue -->
<template>
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
<h3 class="text-xl font-semibold text-gray-900 dark:text-white mb-2">
{{ title }}
</h3>
<p class="text-gray-600 dark:text-gray-400">
<slot />
</p>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
required: true
}
}
}
</script>
<!-- Usage -->
<Card title="Feature Title">
This is the card content that adapts to dark mode.
</Card>vue
<!-- Card.vue -->
<template>
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
<h3 class="text-xl font-semibold text-gray-900 dark:text-white mb-2">
{{ title }}
</h3>
<p class="text-gray-600 dark:text-gray-400">
<slot />
</p>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
required: true
}
}
}
</script>
<!-- 使用示例 -->
<Card title="功能标题">
这是适配深色模式的卡片内容。
</Card>Svelte Components
Svelte组件
svelte
<!-- Alert.svelte -->
<script>
export let type = 'info'; // info, success, warning, error
const styles = {
info: 'bg-blue-50 border-blue-200 text-blue-800',
success: 'bg-green-50 border-green-200 text-green-800',
warning: 'bg-yellow-50 border-yellow-200 text-yellow-800',
error: 'bg-red-50 border-red-200 text-red-800'
};
</script>
<div class="border-l-4 p-4 {styles[type]}" role="alert">
<slot />
</div>
<!-- Usage -->
<Alert type="success">
Your changes have been saved successfully!
</Alert>svelte
<!-- Alert.svelte -->
<script>
export let type = 'info'; // info, success, warning, error
const styles = {
info: 'bg-blue-50 border-blue-200 text-blue-800',
success: 'bg-green-50 border-green-200 text-green-800',
warning: 'bg-yellow-50 border-yellow-200 text-yellow-800',
error: 'bg-red-50 border-red-200 text-red-800'
};
</script>
<div class="border-l-4 p-4 {styles[type]}" role="alert">
<slot />
</div>
<!-- 使用示例 -->
<Alert type="success">
您的更改已成功保存!
</Alert>CSS Component Classes
CSS组件类
For non-component frameworks or shared styles:
css
/* app.css */
@import "tailwindcss";
/* Component layer for reusable patterns */
@layer components {
.btn {
@apply font-bold py-2 px-4 rounded transition;
}
.btn-primary {
@apply bg-blue-500 text-white;
@apply hover:bg-blue-600;
@apply focus:outline-2 focus:outline-offset-2 focus:outline-blue-500;
}
.btn-secondary {
@apply bg-gray-200 text-gray-900;
@apply hover:bg-gray-300;
}
.card {
@apply bg-white rounded-lg shadow-xl p-6;
@apply dark:bg-gray-800;
}
.input-field {
@apply border border-gray-300 rounded px-3 py-2;
@apply focus:border-blue-500 focus:ring-2 focus:ring-blue-200;
@apply dark:bg-gray-700 dark:border-gray-600;
}
}html
<!-- Using component classes -->
<button class="btn btn-primary">Primary Action</button>
<div class="card">
<h3>Card Title</h3>
<p>Card content</p>
</div>
<input class="input-field" placeholder="Enter text..." />适用于非组件框架或共享样式:
css
/* app.css */
@import "tailwindcss";
/* 组件层用于可复用模式 */
@layer components {
.btn {
@apply font-bold py-2 px-4 rounded transition;
}
.btn-primary {
@apply bg-blue-500 text-white;
@apply hover:bg-blue-600;
@apply focus:outline-2 focus:outline-offset-2 focus:outline-blue-500;
}
.btn-secondary {
@apply bg-gray-200 text-gray-900;
@apply hover:bg-gray-300;
}
.card {
@apply bg-white rounded-lg shadow-xl p-6;
@apply dark:bg-gray-800;
}
.input-field {
@apply border border-gray-300 rounded px-3 py-2;
@apply focus:border-blue-500 focus:ring-2 focus:ring-blue-200;
@apply dark:bg-gray-700 dark:border-gray-600;
}
}html
<!-- 使用组件类 -->
<button class="btn btn-primary">主要操作</button>
<div class="card">
<h3>卡片标题</h3>
<p>卡片内容</p>
</div>
<input class="input-field" placeholder="输入文本..." />Theme Customization
主题自定义
Extending the Theme
扩展主题
css
/* app.css */
@import "tailwindcss";
@theme {
/* Custom colors */
--color-primary: #6366f1;
--color-secondary: #8b5cf6;
--color-brand-blue: #3b82f6;
--color-brand-purple: #a855f7;
/* Custom spacing */
--spacing-18: 4.5rem;
--spacing-72: 18rem;
/* Custom breakpoints */
--breakpoint-xs: 30rem;
--breakpoint-3xl: 120rem;
/* Custom fonts */
--font-display: "Montserrat", sans-serif;
--font-body: "Inter", sans-serif;
/* Custom shadows */
--shadow-glow: 0 0 20px rgba(99, 102, 241, 0.5);
/* Custom border radius */
--radius-4xl: 2rem;
/* Custom z-index */
--z-index-dropdown: 1000;
--z-index-modal: 2000;
}html
<!-- Using custom theme values -->
<div class="bg-primary text-white">Primary color</div>
<div class="font-display text-4xl">Display font</div>
<div class="shadow-glow rounded-4xl">Custom shadow and radius</div>
<div class="xs:grid-cols-2 3xl:grid-cols-6">Custom breakpoints</div>css
/* app.css */
@import "tailwindcss";
@theme {
/* 自定义颜色 */
--color-primary: #6366f1;
--color-secondary: #8b5cf6;
--color-brand-blue: #3b82f6;
--color-brand-purple: #a855f7;
/* 自定义间距 */
--spacing-18: 4.5rem;
--spacing-72: 18rem;
/* 自定义断点 */
--breakpoint-xs: 30rem; /* 480px */
--breakpoint-3xl: 120rem; /* 1920px */
/* 自定义字体 */
--font-display: "Montserrat", sans-serif;
--font-body: "Inter", sans-serif;
/* 自定义阴影 */
--shadow-glow: 0 0 20px rgba(99, 102, 241, 0.5);
/* 自定义边框圆角 */
--radius-4xl: 2rem;
/* 自定义z-index */
--z-index-dropdown: 1000;
--z-index-modal: 2000;
}html
<!-- 使用自定义主题值 -->
<div class="bg-primary text-white">主色调</div>
<div class="font-display text-4xl">展示字体</div>
<div class="shadow-glow rounded-4xl">自定义阴影和圆角</div>
<div class="xs:grid-cols-2 3xl:grid-cols-6">自定义断点</div>Using CSS Variables
使用CSS变量
css
/* Dynamic theming with CSS variables */
@import "tailwindcss";
@theme {
--color-primary-50: oklch(0.95 0.02 250);
--color-primary-100: oklch(0.90 0.04 250);
--color-primary-200: oklch(0.85 0.08 250);
--color-primary-500: oklch(0.55 0.22 250);
--color-primary-900: oklch(0.25 0.15 250);
}html
<!-- Arbitrary values with CSS variables -->
<div class="bg-[var(--color-primary-500)]">
Using CSS variable
</div>
<!-- Setting CSS variables inline -->
<div class="[--spacing:1rem] lg:[--spacing:2rem]">
<div class="p-[var(--spacing)]">
Responsive custom property
</div>
</div>css
/* 使用CSS变量实现动态主题 */
@import "tailwindcss";
@theme {
--color-primary-50: oklch(0.95 0.02 250);
--color-primary-100: oklch(0.90 0.04 250);
--color-primary-200: oklch(0.85 0.08 250);
--color-primary-500: oklch(0.55 0.22 250);
--color-primary-900: oklch(0.25 0.15 250);
}html
<!-- 使用CSS变量的任意值 -->
<div class="bg-[var(--color-primary-500)]">
使用CSS变量
</div>
<!-- 内联设置CSS变量 -->
<div class="[--spacing:1rem] lg:[--spacing:2rem]">
<div class="p-[var(--spacing)]">
响应式自定义属性
</div>
</div>Custom Utilities
自定义工具类
Simple Custom Utilities
简单自定义工具类
css
/* app.css */
@import "tailwindcss";
/* Simple utility */
@utility content-auto {
content-visibility: auto;
}
/* Complex utility with nesting */
@utility scrollbar-hidden {
&::-webkit-scrollbar {
display: none;
}
scrollbar-width: none;
}html
<!-- Using custom utilities -->
<div class="content-auto hover:content-auto">
Supports all variants automatically
</div>
<div class="scrollbar-hidden">
Hidden scrollbar
</div>css
/* app.css */
@import "tailwindcss";
/* 简单工具类 */
@utility content-auto {
content-visibility: auto;
}
/* 带嵌套的复杂工具类 */
@utility scrollbar-hidden {
&::-webkit-scrollbar {
display: none;
}
scrollbar-width: none;
}html
<!-- 使用自定义工具类 -->
<div class="content-auto hover:content-auto">
自动支持所有变体
</div>
<div class="scrollbar-hidden">
隐藏滚动条
</div>Functional Custom Utilities
功能性自定义工具类
css
/* app.css */
@import "tailwindcss";
/* Define theme values */
@theme {
--tab-size-2: 2;
--tab-size-4: 4;
--tab-size-8: 8;
}
/* Functional utility accepting arguments */
@utility tab-* {
tab-size: --value(--tab-size-*);
}
/* Utility with modifiers */
@utility text-* {
font-size: --value(--text-*, [length]);
line-height: --modifier(--leading-*, [length], [*]);
}
/* Supporting arbitrary values */
@utility opacity-* {
opacity: --value([percentage]);
opacity: calc(--value(integer) * 1%);
opacity: --value(--opacity-*);
}html
<!-- Using functional utilities -->
<div class="tab-4">Tab size 4</div>
<div class="tab-[12]">Arbitrary tab size</div>
<p class="text-2xl/relaxed">Font size with line height modifier</p>
<div class="opacity-50">50% opacity from theme</div>
<div class="opacity-[0.35]">Arbitrary opacity</div>css
/* app.css */
@import "tailwindcss";
/* 定义主题值 */
@theme {
--tab-size-2: 2;
--tab-size-4: 4;
--tab-size-8: 8;
}
/* 接受参数的功能性工具类 */
@utility tab-* {
tab-size: --value(--tab-size-*);
}
/* 带修饰符的工具类 */
@utility text-* {
font-size: --value(--text-*, [length]);
line-height: --modifier(--leading-*, [length], [*]);
}
/* 支持任意值 */
@utility opacity-* {
opacity: --value([percentage]);
opacity: calc(--value(integer) * 1%);
opacity: --value(--opacity-*);
}html
<!-- 使用功能性工具类 -->
<div class="tab-4">制表符尺寸4</div>
<div class="tab-[12]">任意制表符尺寸</div>
<p class="text-2xl/relaxed">带行高修饰符的字号</p>
<div class="opacity-50">主题定义的50%不透明度</div>
<div class="opacity-[0.35]">任意不透明度</div>Production Optimization
生产环境优化
Build Configuration
构建配置
javascript
// vite.config.ts
import { defineConfig } from 'vite'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [
tailwindcss(),
],
build: {
minify: 'terser',
cssMinify: true,
}
})javascript
// vite.config.ts
import { defineConfig } from 'vite'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [
tailwindcss(),
],
build: {
minify: 'terser',
cssMinify: true,
}
})Content Configuration
内容配置
Ensure Tailwind scans all files:
css
/* app.css */
@import "tailwindcss";
@source "../../**/*.{html,js,jsx,ts,tsx,vue,svelte}";确保Tailwind扫描所有文件:
css
/* app.css */
@import "tailwindcss";
@source "../../**/*.{html,js,jsx,ts,tsx,vue,svelte}";Performance Best Practices
性能最佳实践
-
Use JIT Mode (enabled by default in v4)
- Only generates CSS for classes you use
- Fast build times
- Smaller file sizes
-
Minimize Arbitrary Values
- Use theme values when possible
- Arbitrary values prevent reuse and increase CSS size
-
Avoid Deep Nesting
- Keep utility combinations reasonable
- Extract components for complex patterns
-
Optimize Imageshtml
<img class="w-full h-auto" src="/image.jpg" loading="lazy" decoding="async" /> -
Use CSS Containmenthtml
<div class="content-auto"> Browser can optimize rendering </div>
-
使用JIT模式(v4默认启用)
- 仅生成实际使用的类对应的CSS
- 构建速度更快
- 文件体积更小
-
减少任意值的使用
- 尽可能使用主题值
- 任意值会降低复用性并增加CSS体积
-
避免深层嵌套
- 保持工具类组合合理
- 为复杂模式提取组件
-
优化图片html
<img class="w-full h-auto" src="/image.jpg" loading="lazy" decoding="async" /> -
使用CSS包含html
<div class="content-auto"> 浏览器可优化渲染 </div>
Production Build Checklist
生产构建检查清单
- Enable CSS minification
- Configure content sources correctly
- Remove unused custom utilities
- Optimize image assets
- Test dark mode variants
- Verify responsive breakpoints
- Check accessibility (contrast, focus states)
- Test performance (Lighthouse scores)
- 启用CSS压缩
- 正确配置内容源
- 删除未使用的自定义工具类
- 优化图片资源
- 测试深色模式变体
- 验证响应式断点
- 检查可访问性(对比度、聚焦状态)
- 测试性能(Lighthouse评分)
Plugins and Extensions
插件与扩展
Official Plugins
官方插件
Typography Plugin
Typography插件
bash
npm install @tailwindcss/typographyhtml
<!-- Beautiful typography for markdown/CMS content -->
<article class="prose lg:prose-xl dark:prose-invert">
<h1>Article Title</h1>
<p>Automatically styled content with sensible defaults.</p>
</article>bash
npm install @tailwindcss/typographyhtml
<!-- 为markdown/CMS内容提供美观的排版 -->
<article class="prose lg:prose-xl dark:prose-invert">
<h1>文章标题</h1>
<p>自动应用样式的内容,具备合理的默认值。</p>
</article>Forms Plugin
Forms插件
bash
npm install @tailwindcss/formshtml
<!-- Better default form styles -->
<form class="space-y-4">
<input type="text" class="form-input rounded-md" />
<select class="form-select rounded-md"></select>
<textarea class="form-textarea rounded-md"></textarea>
</form>bash
npm install @tailwindcss/formshtml
<!-- 更优的默认表单样式 -->
<form class="space-y-4">
<input type="text" class="form-input rounded-md" />
<select class="form-select rounded-md"></select>
<textarea class="form-textarea rounded-md"></textarea>
</form>Container Queries Plugin
Container Queries插件
bash
npm install @tailwindcss/container-querieshtml
<div class="@container">
<div class="@lg:grid-cols-3">
Responds to container, not viewport
</div>
</div>bash
npm install @tailwindcss/container-querieshtml
<div class="@container">
<div class="@lg:grid-cols-3">
响应容器尺寸而非视口尺寸
</div>
</div>Framework Integration
框架集成
React / Next.js
React / Next.js
typescript
// tailwind.config.ts
import type { Config } from 'tailwindcss'
export default {
content: [
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
'./app/**/*.{js,ts,jsx,tsx,mdx}',
],
} satisfies Configjsx
// Component with Tailwind
export default function Hero() {
return (
<section className="bg-gradient-to-r from-blue-500 to-purple-600 text-white py-20">
<div className="container mx-auto px-4">
<h1 className="text-5xl font-bold mb-4">Welcome</h1>
<p className="text-xl">Beautiful UI with Tailwind CSS</p>
</div>
</section>
)
}typescript
// tailwind.config.ts
import type { Config } from 'tailwindcss'
export default {
content: [
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
'./app/**/*.{js,ts,jsx,tsx,mdx}',
],
} satisfies Configjsx
// 使用Tailwind的组件
export default function Hero() {
return (
<section className="bg-gradient-to-r from-blue-500 to-purple-600 text-white py-20">
<div className="container mx-auto px-4">
<h1 className="text-5xl font-bold mb-4">欢迎</h1>
<p className="text-xl">使用Tailwind CSS构建美观UI</p>
</div>
</section>
)
}Vue / Nuxt
Vue / Nuxt
typescript
// nuxt.config.ts
import tailwindcss from "@tailwindcss/vite";
export default defineNuxtConfig({
vite: {
plugins: [tailwindcss()],
},
})typescript
// nuxt.config.ts
import tailwindcss from "@tailwindcss/vite";
export default defineNuxtConfig({
vite: {
plugins: [tailwindcss()],
},
})Svelte / SvelteKit
Svelte / SvelteKit
typescript
// vite.config.ts
import { sveltekit } from '@sveltejs/kit/vite';
import tailwindcss from '@tailwindcss/vite';
export default {
plugins: [tailwindcss(), sveltekit()],
};typescript
// vite.config.ts
import { sveltekit } from '@sveltejs/kit/vite';
import tailwindcss from '@tailwindcss/vite';
export default {
plugins: [tailwindcss(), sveltekit()],
};Best Practices
最佳实践
Naming and Organization
命名与组织
-
Use Semantic HTMLhtml
<!-- Good --> <article class="bg-white rounded-lg p-6"> <h2 class="text-2xl font-bold">Title</h2> </article> <!-- Avoid --> <div class="bg-white rounded-lg p-6"> <div class="text-2xl font-bold">Title</div> </div> -
Order Utilities Consistentlyhtml
<!-- Suggested order: layout → spacing → sizing → typography → visual → misc --> <div class=" flex items-center justify-between p-4 mx-auto w-full max-w-4xl text-lg font-semibold bg-white rounded-lg shadow-md hover:shadow-lg transition "> -
Extract Repeated Patternsjsx
// Don't repeat long class strings const cardClasses = "bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6"; <div className={cardClasses}>Card 1</div> <div className={cardClasses}>Card 2</div>
-
使用语义化HTMLhtml
<!-- 推荐 --> <article class="bg-white rounded-lg p-6"> <h2 class="text-2xl font-bold">标题</h2> </article> <!-- 避免 --> <div class="bg-white rounded-lg p-6"> <div class="text-2xl font-bold">标题</div> </div> -
保持工具类顺序一致html
<!-- 建议顺序:布局 → 间距 → 尺寸 → 排版 → 视觉 → 其他 --> <div class=" flex items-center justify-between p-4 mx-auto w-full max-w-4xl text-lg font-semibold bg-white rounded-lg shadow-md hover:shadow-lg transition "> -
提取重复模式jsx
// 不要重复冗长的类字符串 const cardClasses = "bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6"; <div className={cardClasses}>卡片1</div> <div className={cardClasses}>卡片2</div>
Accessibility
可访问性
html
<!-- Focus states -->
<button class="focus:outline-2 focus:outline-offset-2 focus:outline-blue-500">
Accessible button
</button>
<!-- Screen reader only -->
<span class="sr-only">Additional context for screen readers</span>
<!-- High contrast mode -->
<div class="border border-gray-300 forced-colors:border-current">
Adapts to forced colors mode
</div>
<!-- Reduced motion -->
<div class="transition-transform motion-reduce:transition-none">
Respects prefers-reduced-motion
</div>html
<!-- 聚焦状态 -->
<button class="focus:outline-2 focus:outline-offset-2 focus:outline-blue-500">
可访问按钮
</button>
<!-- 仅屏幕阅读器可见 -->
<span class="sr-only">为屏幕阅读器提供额外上下文</span>
<!-- 高对比度模式 -->
<div class="border border-gray-300 forced-colors:border-current">
适配强制颜色模式
</div>
<!-- 减少动画 -->
<div class="transition-transform motion-reduce:transition-none">
尊重prefers-reduced-motion设置
</div>Performance
性能
-
Avoid Inline Styles for Dynamic Valuesjsx
// Good - use CSS variables <button style={{ backgroundColor: buttonColor }} className="rounded-md px-3 py-1.5" > // Avoid - generates unique CSS for each color <button className={`bg-[${buttonColor}]`}> -
Leverage Purging
- Ensure content paths are correct
- Remove unused custom utilities
- Test production builds
-
Optimize for First Painthtml
<!-- Inline critical CSS in <head> --> <style> .hero { /* Critical above-fold styles */ } </style>
-
避免为动态值使用内联样式jsx
// 推荐 - 使用CSS变量 <button style={{ backgroundColor: buttonColor }} className="rounded-md px-3 py-1.5" > // 避免 - 为每种颜色生成唯一CSS <button className={`bg-[${buttonColor}]`}> -
利用清理功能
- 确保内容路径正确
- 删除未使用的自定义工具类
- 测试生产构建
-
优化首次绘制html
<!-- 在<head>中内联关键CSS --> <style> .hero { /* 首屏关键样式 */ } </style>
Common Patterns
常见模式
Navigation Bar
导航栏
html
<nav class="bg-white dark:bg-gray-900 shadow-lg">
<div class="container mx-auto px-4">
<div class="flex items-center justify-between h-16">
<!-- Logo -->
<div class="flex items-center">
<img class="h-8 w-auto" src="/logo.svg" alt="Logo" />
</div>
<!-- Desktop Navigation -->
<div class="hidden md:flex items-center space-x-8">
<a href="#" class="text-gray-900 dark:text-white hover:text-blue-600">Home</a>
<a href="#" class="text-gray-900 dark:text-white hover:text-blue-600">About</a>
<a href="#" class="text-gray-900 dark:text-white hover:text-blue-600">Contact</a>
</div>
<!-- Mobile menu button -->
<button class="md:hidden p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800">
<svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
</svg>
</button>
</div>
</div>
</nav>html
<nav class="bg-white dark:bg-gray-900 shadow-lg">
<div class="container mx-auto px-4">
<div class="flex items-center justify-between h-16">
<!-- Logo -->
<div class="flex items-center">
<img class="h-8 w-auto" src="/logo.svg" alt="Logo" />
</div>
<!-- 桌面端导航 -->
<div class="hidden md:flex items-center space-x-8">
<a href="#" class="text-gray-900 dark:text-white hover:text-blue-600">首页</a>
<a href="#" class="text-gray-900 dark:text-white hover:text-blue-600">关于我们</a>
<a href="#" class="text-gray-900 dark:text-white hover:text-blue-600">联系我们</a>
</div>
<!-- 移动端菜单按钮 -->
<button class="md:hidden p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800">
<svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
</svg>
</button>
</div>
</div>
</nav>Hero Section
Hero区域
html
<section class="relative bg-gradient-to-r from-blue-600 to-purple-600 text-white py-20 lg:py-32">
<div class="container mx-auto px-4">
<div class="max-w-3xl mx-auto text-center">
<h1 class="text-4xl md:text-5xl lg:text-6xl font-bold mb-6">
Build Amazing Websites
</h1>
<p class="text-xl md:text-2xl mb-8 text-blue-100">
Create beautiful, responsive designs with Tailwind CSS
</p>
<div class="flex flex-col sm:flex-row gap-4 justify-center">
<button class="bg-white text-blue-600 px-8 py-3 rounded-lg font-semibold hover:bg-blue-50 transition">
Get Started
</button>
<button class="border-2 border-white text-white px-8 py-3 rounded-lg font-semibold hover:bg-white hover:text-blue-600 transition">
Learn More
</button>
</div>
</div>
</div>
</section>html
<section class="relative bg-gradient-to-r from-blue-600 to-purple-600 text-white py-20 lg:py-32">
<div class="container mx-auto px-4">
<div class="max-w-3xl mx-auto text-center">
<h1 class="text-4xl md:text-5xl lg:text-6xl font-bold mb-6">
构建出色网站
</h1>
<p class="text-xl md:text-2xl mb-8 text-blue-100">
使用Tailwind CSS创建美观、响应式的设计
</p>
<div class="flex flex-col sm:flex-row gap-4 justify-center">
<button class="bg-white text-blue-600 px-8 py-3 rounded-lg font-semibold hover:bg-blue-50 transition">
开始使用
</button>
<button class="border-2 border-white text-white px-8 py-3 rounded-lg font-semibold hover:bg-white hover:text-blue-600 transition">
了解更多
</button>
</div>
</div>
</div>
</section>Feature Grid
功能网格
html
<section class="py-16 bg-gray-50 dark:bg-gray-900">
<div class="container mx-auto px-4">
<h2 class="text-3xl font-bold text-center mb-12 text-gray-900 dark:text-white">
Our Features
</h2>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
<!-- Feature Card -->
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 hover:shadow-xl transition">
<div class="w-12 h-12 bg-blue-500 rounded-lg flex items-center justify-center mb-4">
<svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
</div>
<h3 class="text-xl font-semibold mb-2 text-gray-900 dark:text-white">
Lightning Fast
</h3>
<p class="text-gray-600 dark:text-gray-400">
Build and ship faster with utility-first CSS approach.
</p>
</div>
<!-- More feature cards... -->
</div>
</div>
</section>html
<section class="py-16 bg-gray-50 dark:bg-gray-900">
<div class="container mx-auto px-4">
<h2 class="text-3xl font-bold text-center mb-12 text-gray-900 dark:text-white">
我们的功能
</h2>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
<!-- 功能卡片 -->
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 hover:shadow-xl transition">
<div class="w-12 h-12 bg-blue-500 rounded-lg flex items-center justify-center mb-4">
<svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
</div>
<h3 class="text-xl font-semibold mb-2 text-gray-900 dark:text-white">
极速体验
</h3>
<p class="text-gray-600 dark:text-gray-400">
使用实用优先的CSS方法更快地构建和交付。
</p>
</div>
<!-- 更多功能卡片... -->
</div>
</div>
</section>Troubleshooting
故障排除
Common Issues
常见问题
Styles not applying
- Check content configuration in CSS
- Ensure classes are written correctly (no typos)
- Verify build process is running
- Check for CSS specificity conflicts
Dark mode not working
- Verify dark variant configuration
- Check if dark class is applied to HTML element
- Ensure localStorage logic is correct
- Test system preference detection
Responsive classes not working
- Verify breakpoint configuration
- Check mobile-first approach (base → larger)
- Ensure viewport meta tag is present
- Test in actual devices/browser dev tools
Build is slow
- Use JIT mode (default in v4)
- Optimize content paths
- Remove unnecessary dependencies
- Check for circular imports
File size too large
- Configure content paths correctly
- Remove unused custom utilities
- Enable CSS minification
- Audit third-party dependencies
样式未生效
- 检查CSS中的内容配置
- 确保类名书写正确(无拼写错误)
- 验证构建流程是否在运行
- 检查CSS特异性冲突
深色模式不工作
- 验证深色变体配置
- 检查HTML元素是否应用了dark类
- 确保localStorage逻辑正确
- 测试系统偏好检测
响应式类不工作
- 验证断点配置
- 检查移动优先方法(基础 → 更大屏幕)
- 确保存在视口元标签
- 在实际设备/浏览器开发者工具中测试
构建速度慢
- 使用JIT模式(v4默认)
- 优化内容路径
- 删除不必要的依赖
- 检查循环导入
文件体积过大
- 正确配置内容路径
- 删除未使用的自定义工具类
- 启用CSS压缩
- 审核第三方依赖
Resources
资源
- Official Documentation: https://tailwindcss.com
- Tailwind UI Components: https://tailwindui.com
- Headless UI: https://headlessui.com
- Tailwind Play (Online Editor): https://play.tailwindcss.com
- GitHub Repository: https://github.com/tailwindlabs/tailwindcss
- Community Discord: https://tailwindcss.com/discord
- YouTube Channel: https://www.youtube.com/tailwindlabs
Skill Version: 1.0.0
Last Updated: October 2025
Skill Category: CSS Framework, UI Development, Design Systems
Compatible With: React, Vue, Svelte, Next.js, Nuxt, SvelteKit, Astro, and vanilla HTML
- 官方文档:https://tailwindcss.com
- Tailwind UI组件:https://tailwindui.com
- Headless UI:https://headlessui.com
- Tailwind Play(在线编辑器):https://play.tailwindcss.com
- GitHub仓库:https://github.com/tailwindlabs/tailwindcss
- 社区Discord:https://tailwindcss.com/discord
- YouTube频道:https://www.youtube.com/tailwindlabs
指南版本: 1.0.0
最后更新: 2025年10月
指南分类: CSS框架、UI开发、设计系统
兼容框架: React、Vue、Svelte、Next.js、Nuxt、SvelteKit、Astro以及原生HTML