tailwind-css
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTailwind CSS Skill
Tailwind CSS 技能
progressive_disclosure: entry_point: - summary - when_to_use - quick_start sections: core_concepts: - utility_first_approach - responsive_design - configuration advanced: - dark_mode - custom_utilities - plugins - performance_optimization integration: - framework_integration - component_patterns reference: - common_utilities - breakpoints - color_system tokens: entry: 75 full: 4500
progressive_disclosure: entry_point: - summary - when_to_use - quick_start sections: core_concepts: - utility_first_approach - responsive_design - configuration advanced: - dark_mode - custom_utilities - plugins - performance_optimization integration: - framework_integration - component_patterns reference: - common_utilities - breakpoints - color_system tokens: entry: 75 full: 4500
Summary
概述
Tailwind CSS is a utility-first CSS framework that provides low-level utility classes to build custom designs without writing CSS. It offers responsive design, dark mode, customization through configuration, and integrates seamlessly with modern frameworks.
Tailwind CSS是一个优先实用工具类的CSS框架,提供底层实用工具类来构建自定义设计,无需编写CSS。它支持响应式设计、深色模式,可通过配置进行自定义,并且能与现代框架无缝集成。
When to Use
适用场景
Best for:
- Rapid prototyping with consistent design systems
- Component-based frameworks (React, Vue, Svelte)
- Projects requiring responsive and dark mode support
- Teams wanting to avoid CSS file maintenance
- Design systems with standardized spacing/colors
Consider alternatives when:
- Team unfamiliar with utility-first approach (learning curve)
- Project requires extensive custom CSS animations
- Legacy browser support needed (IE11)
- Minimal CSS footprint required without build process
最适合:
- 使用一致设计系统进行快速原型开发
- 基于组件的框架(React、Vue、Svelte)
- 需要响应式和深色模式支持的项目
- 希望避免维护CSS文件的团队
- 具有标准化间距/颜色的设计系统
考虑替代方案的情况:
- 团队不熟悉优先实用工具类方法(存在学习曲线)
- 项目需要大量自定义CSS动画
- 需要兼容旧版浏览器(IE11)
- 无需构建流程且要求CSS体积极小的项目
Quick Start
快速开始
Installation
安装
bash
undefinedbash
undefinednpm
npm
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
yarn
yarn
yarn add -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
yarn add -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
pnpm
pnpm
pnpm add -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
undefinedpnpm add -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
undefinedConfiguration
配置
tailwind.config.js:
javascript
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
"./public/index.html",
],
theme: {
extend: {},
},
plugins: [],
}tailwind.config.js:
javascript
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
"./public/index.html",
],
theme: {
extend: {},
},
plugins: [],
}Basic CSS Setup
基础CSS设置
styles/globals.css:
css
@tailwind base;
@tailwind components;
@tailwind utilities;styles/globals.css:
css
@tailwind base;
@tailwind components;
@tailwind utilities;First Component
第一个组件
jsx
// Simple button with Tailwind utilities
function Button({ children, variant = 'primary' }) {
const baseClasses = "px-4 py-2 rounded-lg font-medium transition-colors";
const variants = {
primary: "bg-blue-600 text-white hover:bg-blue-700",
secondary: "bg-gray-200 text-gray-900 hover:bg-gray-300",
danger: "bg-red-600 text-white hover:bg-red-700"
};
return (
<button className={`${baseClasses} ${variants[variant]}`}>
{children}
</button>
);
}jsx
// 使用Tailwind工具类的简单按钮
function Button({ children, variant = 'primary' }) {
const baseClasses = "px-4 py-2 rounded-lg font-medium transition-colors";
const variants = {
primary: "bg-blue-600 text-white hover:bg-blue-700",
secondary: "bg-gray-200 text-gray-900 hover:bg-gray-300",
danger: "bg-red-600 text-white hover:bg-red-700"
};
return (
<button className={`${baseClasses} ${variants[variant]}`}>
{children}
</button>
);
}Core Concepts
核心概念
Utility-First Approach
优先实用工具类方法
Tailwind provides single-purpose utility classes that map directly to CSS properties.
Tailwind提供单一用途的实用工具类,直接映射到CSS属性。
Layout Utilities
布局实用工具
Flexbox:
jsx
// Centered flex container
<div className="flex items-center justify-center">
<div>Centered content</div>
</div>
// Responsive flex direction
<div className="flex flex-col md:flex-row gap-4">
<div className="flex-1">Column 1</div>
<div className="flex-1">Column 2</div>
</div>
// Flex wrapping and alignment
<div className="flex flex-wrap items-start justify-between">
<div className="w-1/2 md:w-1/4">Item</div>
<div className="w-1/2 md:w-1/4">Item</div>
</div>Grid:
jsx
// Basic grid
<div className="grid grid-cols-3 gap-4">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
// Responsive grid
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="col-span-1 md:col-span-2">Wide item</div>
<div>Item</div>
<div>Item</div>
</div>
// Auto-fit grid
<div className="grid grid-cols-[repeat(auto-fit,minmax(250px,1fr))] gap-4">
<div>Auto-sized item</div>
<div>Auto-sized item</div>
</div>Flexbox:
jsx
// 居中的flex容器
<div className="flex items-center justify-center">
<div>居中内容</div>
</div>
// 响应式flex方向
<div className="flex flex-col md:flex-row gap-4">
<div className="flex-1">列1</div>
<div className="flex-1">列2</div>
</div>
// Flex换行与对齐
<div className="flex flex-wrap items-start justify-between">
<div className="w-1/2 md:w-1/4">项目</div>
<div className="w-1/2 md:w-1/4">项目</div>
</div>Grid:
jsx
// 基础网格
<div className="grid grid-cols-3 gap-4">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
// 响应式网格
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="col-span-1 md:col-span-2">宽项目</div>
<div>项目</div>
<div>项目</div>
</div>
// 自动适配网格
<div className="grid grid-cols-[repeat(auto-fit,minmax(250px,1fr))] gap-4">
<div>自动适配项目</div>
<div>自动适配项目</div>
</div>Spacing System
间距系统
Padding and Margin:
jsx
// Uniform spacing
<div className="p-4">Padding all sides</div>
<div className="m-8">Margin all sides</div>
// Directional spacing
<div className="pt-4 pb-8 px-6">Top 4, bottom 8, horizontal 6</div>
<div className="ml-auto mr-0">Right-aligned with margin</div>
// Negative margins
<div className="mt-4 -mb-2">Overlap bottom</div>
// Responsive spacing
<div className="p-2 md:p-4 lg:p-8">Responsive padding</div>Space Between:
jsx
// Gap between children
<div className="flex gap-4">
<div>Item 1</div>
<div>Item 2</div>
</div>
// Responsive gap
<div className="grid grid-cols-3 gap-2 md:gap-4 lg:gap-6">
<div>1</div>
<div>2</div>
<div>3</div>
</div>内边距与外边距:
jsx
// 统一间距
<div className="p-4">四边内边距</div>
<div className="m-8">四边外边距</div>
// 方向间距
<div className="pt-4 pb-8 px-6">上边4,下边8,水平方向6</div>
<div className="ml-auto mr-0">右对齐外边距</div>
// 负外边距
<div className="mt-4 -mb-2">底部重叠</div>
// 响应式间距
<div className="p-2 md:p-4 lg:p-8">响应式内边距</div>子元素间距:
jsx
// 子元素之间的间距
<div className="flex gap-4">
<div>项目1</div>
<div>项目2</div>
</div>
// 响应式间距
<div className="grid grid-cols-3 gap-2 md:gap-4 lg:gap-6">
<div>1</div>
<div>2</div>
<div>3</div>
</div>Typography
排版
jsx
// Font sizes and weights
<h1 className="text-4xl font-bold">Heading</h1>
<p className="text-base font-normal leading-relaxed">Paragraph</p>
<span className="text-sm font-medium text-gray-600">Caption</span>
// Text alignment and decoration
<p className="text-center underline">Centered underlined text</p>
<p className="text-right line-through">Right-aligned strikethrough</p>
// Responsive typography
<h1 className="text-2xl md:text-4xl lg:text-6xl font-bold">
Responsive heading
</h1>
// Text overflow handling
<p className="truncate">This text will be truncated with ellipsis...</p>
<p className="line-clamp-3">
This text will be clamped to 3 lines with ellipsis...
</p>jsx
// 字体大小与字重
<h1 className="text-4xl font-bold">标题</h1>
<p className="text-base font-normal leading-relaxed">段落</p>
<span className="text-sm font-medium text-gray-600">说明文字</span>
// 文本对齐与装饰
<p className="text-center underline">居中带下划线文本</p>
<p className="text-right line-through">右对齐删除线文本</p>
// 响应式排版
<h1 className="text-2xl md:text-4xl lg:text-6xl font-bold">
响应式标题
</h1>
// 文本溢出处理
<p className="truncate">此文本将被截断并显示省略号...</p>
<p className="line-clamp-3">
此文本将被限制为3行并显示省略号...
</p>Colors
颜色
jsx
// Background colors
<div className="bg-blue-500">Blue background</div>
<div className="bg-gray-100 dark:bg-gray-800">Adaptive background</div>
// Text colors
<p className="text-red-600">Red text</p>
<p className="text-gray-700 dark:text-gray-300">Adaptive text</p>
// Border colors
<div className="border border-gray-300 hover:border-blue-500">
Hover border
</div>
// Opacity modifiers
<div className="bg-blue-500/50">50% opacity blue</div>
<div className="bg-black/25">25% opacity black</div>jsx
// 背景色
<div className="bg-blue-500">蓝色背景</div>
<div className="bg-gray-100 dark:bg-gray-800">自适应背景</div>
// 文本颜色
<p className="text-red-600">红色文本</p>
<p className="text-gray-700 dark:text-gray-300">自适应文本</p>
// 边框颜色
<div className="border border-gray-300 hover:border-blue-500">
悬停边框
</div>
// 透明度修饰
<div className="bg-blue-500/50">50%透明度蓝色</div>
<div className="bg-black/25">25%透明度黑色</div>Responsive Design
响应式设计
Tailwind uses mobile-first breakpoint system.
Tailwind采用移动优先的断点系统。
Breakpoints
断点
javascript
// Default breakpoints (tailwind.config.js)
{
theme: {
screens: {
'sm': '640px', // Small devices
'md': '768px', // Medium devices
'lg': '1024px', // Large devices
'xl': '1280px', // Extra large
'2xl': '1536px', // 2X extra large
}
}
}javascript
// 默认断点(tailwind.config.js)
{
theme: {
screens: {
'sm': '640px', // 小型设备
'md': '768px', // 中型设备
'lg': '1024px', // 大型设备
'xl': '1280px', // 超大型设备
'2xl': '1536px', // 2倍超大型设备
}
}
}Responsive Patterns
响应式模式
jsx
// Hide/show at breakpoints
<div className="hidden md:block">Visible on desktop</div>
<div className="block md:hidden">Visible on mobile</div>
// Responsive layout
<div className="
flex flex-col // Mobile: stack vertically
md:flex-row // Desktop: horizontal
gap-4 md:gap-8 // Larger gap on desktop
">
<aside className="w-full md:w-64">Sidebar</aside>
<main className="flex-1">Content</main>
</div>
// Responsive grid
<div className="
grid
grid-cols-1 // Mobile: 1 column
sm:grid-cols-2 // Small: 2 columns
lg:grid-cols-3 // Large: 3 columns
xl:grid-cols-4 // XL: 4 columns
gap-4
">
{items.map(item => <Card key={item.id} {...item} />)}
</div>
// Container with responsive padding
<div className="
container mx-auto
px-4 sm:px-6 lg:px-8
max-w-7xl
">
<h1>Responsive container</h1>
</div>jsx
// 不同断点下显示/隐藏
<div className="hidden md:block">桌面端可见</div>
<div className="block md:hidden">移动端可见</div>
// 响应式布局
<div className="
flex flex-col // 移动端:垂直堆叠
md:flex-row // 桌面端:水平排列
gap-4 md:gap-8 // 桌面端使用更大间距
">
<aside className="w-full md:w-64">侧边栏</aside>
<main className="flex-1">内容</main>
</div>
// 响应式网格
<div className="
grid
grid-cols-1 // 移动端:1列
sm:grid-cols-2 // 小型设备:2列
lg:grid-cols-3 // 大型设备:3列
xl:grid-cols-4 // 超大型设备:4列
gap-4
">
{items.map(item => <Card key={item.id} {...item} />)}
</div>
// 带响应式内边距的容器
<div className="
container mx-auto
px-4 sm:px-6 lg:px-8
max-w-7xl
">
<h1>响应式容器</h1>
</div>Configuration
配置
Theme Extension
主题扩展
tailwind.config.js:
javascript
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
theme: {
extend: {
colors: {
brand: {
50: '#f0f9ff',
100: '#e0f2fe',
500: '#0ea5e9',
900: '#0c4a6e',
},
accent: '#ff6b6b',
},
spacing: {
'18': '4.5rem',
'88': '22rem',
'128': '32rem',
},
fontFamily: {
sans: ['Inter', 'system-ui', 'sans-serif'],
display: ['Poppins', 'sans-serif'],
mono: ['Fira Code', 'monospace'],
},
fontSize: {
'2xs': '0.625rem',
'3xl': '2rem',
},
borderRadius: {
'4xl': '2rem',
},
boxShadow: {
'inner-lg': 'inset 0 2px 4px 0 rgb(0 0 0 / 0.1)',
},
animation: {
'slide-in': 'slideIn 0.3s ease-out',
'fade-in': 'fadeIn 0.2s ease-in',
},
keyframes: {
slideIn: {
'0%': { transform: 'translateX(-100%)' },
'100%': { transform: 'translateX(0)' },
},
fadeIn: {
'0%': { opacity: '0' },
'100%': { opacity: '1' },
},
},
},
},
plugins: [],
}tailwind.config.js:
javascript
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
theme: {
extend: {
colors: {
brand: {
50: '#f0f9ff',
100: '#e0f2fe',
500: '#0ea5e9',
900: '#0c4a6e',
},
accent: '#ff6b6b',
},
spacing: {
'18': '4.5rem',
'88': '22rem',
'128': '32rem',
},
fontFamily: {
sans: ['Inter', 'system-ui', 'sans-serif'],
display: ['Poppins', 'sans-serif'],
mono: ['Fira Code', 'monospace'],
},
fontSize: {
'2xs': '0.625rem',
'3xl': '2rem',
},
borderRadius: {
'4xl': '2rem',
},
boxShadow: {
'inner-lg': 'inset 0 2px 4px 0 rgb(0 0 0 / 0.1)',
},
animation: {
'slide-in': 'slideIn 0.3s ease-out',
'fade-in': 'fadeIn 0.2s ease-in',
},
keyframes: {
slideIn: {
'0%': { transform: 'translateX(-100%)' },
'100%': { transform: 'translateX(0)' },
},
fadeIn: {
'0%': { opacity: '0' },
'100%': { opacity: '1' },
},
},
},
},
plugins: [],
}Custom Breakpoints
自定义断点
javascript
module.exports = {
theme: {
screens: {
'xs': '475px',
'sm': '640px',
'md': '768px',
'lg': '1024px',
'xl': '1280px',
'2xl': '1536px',
'3xl': '1920px',
// Custom breakpoints
'tablet': '640px',
'laptop': '1024px',
'desktop': '1280px',
// Max-width breakpoints
'max-md': {'max': '767px'},
},
},
}javascript
module.exports = {
theme: {
screens: {
'xs': '475px',
'sm': '640px',
'md': '768px',
'lg': '1024px',
'xl': '1280px',
'2xl': '1536px',
'3xl': '1920px',
// 自定义断点
'tablet': '640px',
'laptop': '1024px',
'desktop': '1280px',
// 最大宽度断点
'max-md': {'max': '767px'},
},
},
}Advanced Features
高级功能
Dark Mode
深色模式
Class Strategy (Recommended)
类策略(推荐)
tailwind.config.js:
javascript
module.exports = {
darkMode: 'class', // or 'media' for OS preference
// ...
}Implementation:
jsx
// Toggle component
function DarkModeToggle() {
const [isDark, setIsDark] = useState(false);
useEffect(() => {
if (isDark) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}, [isDark]);
return (
<button
onClick={() => setIsDark(!isDark)}
className="p-2 rounded-lg bg-gray-200 dark:bg-gray-700"
>
{isDark ? '🌞' : '🌙'}
</button>
);
}
// Dark mode styles
function Card() {
return (
<div className="
bg-white dark:bg-gray-800
text-gray-900 dark:text-gray-100
border border-gray-200 dark:border-gray-700
shadow-lg dark:shadow-none
">
<h2 className="text-xl font-bold mb-2">Card Title</h2>
<p className="text-gray-600 dark:text-gray-400">
Card content adapts to dark mode
</p>
</div>
);
}tailwind.config.js:
javascript
module.exports = {
darkMode: 'class', // 或使用'media'遵循系统偏好
// ...
}实现:
jsx
// 切换组件
function DarkModeToggle() {
const [isDark, setIsDark] = useState(false);
useEffect(() => {
if (isDark) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}, [isDark]);
return (
<button
onClick={() => setIsDark(!isDark)}
className="p-2 rounded-lg bg-gray-200 dark:bg-gray-700"
>
{isDark ? '🌞' : '🌙'}
</button>
);
}
// 深色模式样式
function Card() {
return (
<div className="
bg-white dark:bg-gray-800
text-gray-900 dark:text-gray-100
border border-gray-200 dark:border-gray-700
shadow-lg dark:shadow-none
">
<h2 className="text-xl font-bold mb-2">卡片标题</h2>
<p className="text-gray-600 dark:text-gray-400">
卡片内容会适配深色模式
</p>
</div>
);
}System Preference Strategy
系统偏好策略
javascript
// tailwind.config.js
module.exports = {
darkMode: 'media', // Uses OS preference
}jsx
// Automatically adapts to system preference
<div className="bg-white dark:bg-gray-900">
Content adapts automatically
</div>javascript
// tailwind.config.js
module.exports = {
darkMode: 'media', // 遵循系统偏好
}jsx
// 自动适配系统偏好
<div className="bg-white dark:bg-gray-900">
内容自动适配
</div>Custom Utilities
自定义实用工具
Adding Custom Utilities
添加自定义实用工具
tailwind.config.js:
javascript
const plugin = require('tailwindcss/plugin');
module.exports = {
plugins: [
plugin(function({ addUtilities, addComponents, theme }) {
// Custom utilities
addUtilities({
'.scrollbar-hide': {
'-ms-overflow-style': 'none',
'scrollbar-width': 'none',
'&::-webkit-scrollbar': {
display: 'none',
},
},
'.text-balance': {
'text-wrap': 'balance',
},
});
// Custom components
addComponents({
'.btn': {
padding: theme('spacing.4'),
borderRadius: theme('borderRadius.lg'),
fontWeight: theme('fontWeight.medium'),
'&:hover': {
opacity: 0.9,
},
},
'.card': {
backgroundColor: theme('colors.white'),
borderRadius: theme('borderRadius.lg'),
padding: theme('spacing.6'),
boxShadow: theme('boxShadow.lg'),
},
});
}),
],
}tailwind.config.js:
javascript
const plugin = require('tailwindcss/plugin');
module.exports = {
plugins: [
plugin(function({ addUtilities, addComponents, theme }) {
// 自定义实用工具
addUtilities({
'.scrollbar-hide': {
'-ms-overflow-style': 'none',
'scrollbar-width': 'none',
'&::-webkit-scrollbar': {
display: 'none',
},
},
'.text-balance': {
'text-wrap': 'balance',
},
});
// 自定义组件
addComponents({
'.btn': {
padding: theme('spacing.4'),
borderRadius: theme('borderRadius.lg'),
fontWeight: theme('fontWeight.medium'),
'&:hover': {
opacity: 0.9,
},
},
'.card': {
backgroundColor: theme('colors.white'),
borderRadius: theme('borderRadius.lg'),
padding: theme('spacing.6'),
boxShadow: theme('boxShadow.lg'),
},
});
}),
],
}Custom Variants
自定义变体
javascript
const plugin = require('tailwindcss/plugin');
module.exports = {
plugins: [
plugin(function({ addVariant }) {
// Custom variant for third child
addVariant('third', '&:nth-child(3)');
// Custom variant for not-last child
addVariant('not-last', '&:not(:last-child)');
// Custom variant for group-hover with specific element
addVariant('group-hover-show', '.group:hover &');
}),
],
}
// Usage
<div className="third:font-bold not-last:border-b">
Custom variant styles
</div>javascript
const plugin = require('tailwindcss/plugin');
module.exports = {
plugins: [
plugin(function({ addVariant }) {
// 第三个子元素的自定义变体
addVariant('third', '&:nth-child(3)');
// 非最后一个子元素的自定义变体
addVariant('not-last', '&:not(:last-child)');
// 特定元素的group-hover自定义变体
addVariant('group-hover-show', '.group:hover &');
}),
],
}
// 使用示例
<div className="third:font-bold not-last:border-b">
自定义变体样式
</div>Plugins
插件
Official Plugins
官方插件
bash
npm install -D @tailwindcss/forms @tailwindcss/typography @tailwindcss/aspect-ratiotailwind.config.js:
javascript
module.exports = {
plugins: [
require('@tailwindcss/forms'),
require('@tailwindcss/typography'),
require('@tailwindcss/aspect-ratio'),
],
}bash
npm install -D @tailwindcss/forms @tailwindcss/typography @tailwindcss/aspect-ratiotailwind.config.js:
javascript
module.exports = {
plugins: [
require('@tailwindcss/forms'),
require('@tailwindcss/typography'),
require('@tailwindcss/aspect-ratio'),
],
}Forms Plugin
表单插件
jsx
// Automatic form styling
<form className="space-y-4">
<input
type="text"
className="
form-input
rounded-lg
border-gray-300
focus:border-blue-500
focus:ring-blue-500
"
placeholder="Name"
/>
<select className="form-select rounded-lg">
<option>Option 1</option>
<option>Option 2</option>
</select>
<label className="flex items-center">
<input type="checkbox" className="form-checkbox text-blue-600" />
<span className="ml-2">Agree to terms</span>
</label>
</form>jsx
// 自动表单样式
<form className="space-y-4">
<input
type="text"
className="
form-input
rounded-lg
border-gray-300
focus:border-blue-500
focus:ring-blue-500
"
placeholder="姓名"
/>
<select className="form-select rounded-lg">
<option>选项1</option>
<option>选项2</option>
</select>
<label className="flex items-center">
<input type="checkbox" className="form-checkbox text-blue-600" />
<span className="ml-2">同意条款</span>
</label>
</form>Typography Plugin
排版插件
jsx
// Beautiful prose styling
<article className="
prose
prose-lg
prose-slate
dark:prose-invert
max-w-none
">
<h1>Article Title</h1>
<p>Automatic typography styles for markdown content...</p>
<ul>
<li>Styled lists</li>
<li>Proper spacing</li>
</ul>
</article>jsx
// 美观的正文样式
<article className="
prose
prose-lg
prose-slate
dark:prose-invert
max-w-none
">
<h1>文章标题</h1>
<p>为markdown内容自动设置排版样式...</p>
<ul>
<li>样式化列表</li>
<li>合适的间距</li>
</ul>
</article>Aspect Ratio Plugin
宽高比插件
jsx
// Maintain aspect ratios
<div className="aspect-w-16 aspect-h-9">
<iframe src="..." className="w-full h-full" />
</div>
<div className="aspect-square">
<img src="..." className="object-cover w-full h-full" />
</div>jsx
// 保持宽高比
<div className="aspect-w-16 aspect-h-9">
<iframe src="..." className="w-full h-full" />
</div>
<div className="aspect-square">
<img src="..." className="object-cover w-full h-full" />
</div>Performance Optimization
性能优化
Content Configuration
内容配置
javascript
// Optimize purge paths
module.exports = {
content: [
'./src/**/*.{js,jsx,ts,tsx}',
'./public/index.html',
// Include component libraries
'./node_modules/@my-ui/**/*.js',
],
// Safelist dynamic classes
safelist: [
'bg-red-500',
'bg-green-500',
{
pattern: /bg-(red|green|blue)-(400|500|600)/,
variants: ['hover', 'focus'],
},
],
}javascript
// 优化清除路径
module.exports = {
content: [
'./src/**/*.{js,jsx,ts,tsx}',
'./public/index.html',
// 包含组件库
'./node_modules/@my-ui/**/*.js',
],
// 安全列表:动态类
safelist: [
'bg-red-500',
'bg-green-500',
{
pattern: /bg-(red|green|blue)-(400|500|600)/,
variants: ['hover', 'focus'],
},
],
}JIT Mode (Default in v3+)
JIT模式(v3+默认启用)
Just-In-Time compilation generates styles on-demand:
jsx
// Arbitrary values work instantly
<div className="top-[117px]">Custom value</div>
<div className="bg-[#1da1f2]">Custom color</div>
<div className="grid-cols-[1fr_500px_2fr]">Custom grid</div>
// No rebuild needed for new utilities
<div className="before:content-['★']">Star before</div>即时编译按需生成样式:
jsx
// 任意值可立即生效
<div className="top-[117px]">自定义值</div>
<div className="bg-[#1da1f2]">自定义颜色</div>
<div className="grid-cols-[1fr_500px_2fr]">自定义网格</div>
// 新增工具类无需重新构建
<div className="before:content-['★']">前面加星号</div>Build Optimization
构建优化
javascript
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
// Production minification
...(process.env.NODE_ENV === 'production'
? { cssnano: {} }
: {}),
},
}javascript
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
// 生产环境压缩
...(process.env.NODE_ENV === 'production'
? { cssnano: {} }
: {}),
},
}Framework Integration
框架集成
React / Next.js
React / Next.js
Installation:
bash
npx create-next-app@latest my-app --tailwind安装:
bash
npx create-next-app@latest my-app --tailwindor add to existing project
或添加到现有项目
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
**next.config.js:**
```javascript
/** @type {import('next').NextConfig} */
module.exports = {
// Tailwind works out of box with Next.js
}_app.tsx:
typescript
import '@/styles/globals.css'
import type { AppProps } from 'next/app'
export default function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}Component Example:
tsx
// components/Button.tsx
import { ButtonHTMLAttributes, forwardRef } from 'react'
import { cva, type VariantProps } from 'class-variance-authority'
const buttonVariants = cva(
"inline-flex items-center justify-center rounded-lg font-medium transition-colors",
{
variants: {
variant: {
default: "bg-blue-600 text-white hover:bg-blue-700",
outline: "border border-gray-300 hover:bg-gray-100",
ghost: "hover:bg-gray-100",
},
size: {
sm: "px-3 py-1.5 text-sm",
md: "px-4 py-2",
lg: "px-6 py-3 text-lg",
},
},
defaultVariants: {
variant: "default",
size: "md",
},
}
)
interface ButtonProps
extends ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {}
const Button = forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, ...props }, ref) => {
return (
<button
ref={ref}
className={buttonVariants({ variant, size, className })}
{...props}
/>
)
}
)
export default Buttonnpm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
**next.config.js:**
```javascript
/** @type {import('next').NextConfig} */
module.exports = {
// Tailwind与Next.js开箱即用
}_app.tsx:
typescript
import '@/styles/globals.css'
import type { AppProps } from 'next/app'
export default function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}组件示例:
tsx
// components/Button.tsx
import { ButtonHTMLAttributes, forwardRef } from 'react'
import { cva, type VariantProps } from 'class-variance-authority'
const buttonVariants = cva(
"inline-flex items-center justify-center rounded-lg font-medium transition-colors",
{
variants: {
variant: {
default: "bg-blue-600 text-white hover:bg-blue-700",
outline: "border border-gray-300 hover:bg-gray-100",
ghost: "hover:bg-gray-100",
},
size: {
sm: "px-3 py-1.5 text-sm",
md: "px-4 py-2",
lg: "px-6 py-3 text-lg",
},
},
defaultVariants: {
variant: "default",
size: "md",
},
}
)
interface ButtonProps
extends ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {}
const Button = forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, ...props }, ref) => {
return (
<button
ref={ref}
className={buttonVariants({ variant, size, className })}
{...props}
/>
)
}
)
export default ButtonSvelteKit
SvelteKit
Installation:
bash
npx sv create my-app安装:
bash
npx sv create my-appSelect Tailwind CSS option
选择Tailwind CSS选项
or add to existing
或添加到现有项目
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
**svelte.config.js:**
```javascript
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
export default {
preprocess: vitePreprocess(),
kit: {
adapter: adapter()
}
};Component Example:
svelte
<!-- Button.svelte -->
<script lang="ts">
export let variant: 'primary' | 'secondary' = 'primary';
export let size: 'sm' | 'md' | 'lg' = 'md';
const variants = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300'
};
const sizes = {
sm: 'px-3 py-1.5 text-sm',
md: 'px-4 py-2',
lg: 'px-6 py-3 text-lg'
};
</script>
<button
class="rounded-lg font-medium transition-colors {variants[variant]} {sizes[size]}"
on:click
>
<slot />
</button>npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
**svelte.config.js:**
```javascript
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
export default {
preprocess: vitePreprocess(),
kit: {
adapter: adapter()
}
};组件示例:
svelte
<!-- Button.svelte -->
<script lang="ts">
export let variant: 'primary' | 'secondary' = 'primary';
export let size: 'sm' | 'md' | 'lg' = 'md';
const variants = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300'
};
const sizes = {
sm: 'px-3 py-1.5 text-sm',
md: 'px-4 py-2',
lg: 'px-6 py-3 text-lg'
};
</script>
<button
class="rounded-lg font-medium transition-colors {variants[variant]} {sizes[size]}"
on:click
>
<slot />
</button>Vue 3
Vue 3
Installation:
bash
npm create vue@latest my-app安装:
bash
npm create vue@latest my-appSelect Tailwind CSS
选择Tailwind CSS
or add to existing
或添加到现有项目
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
**main.ts:**
```typescript
import { createApp } from 'vue'
import App from './App.vue'
import './assets/main.css'
createApp(App).mount('#app')Component Example:
vue
<!-- Button.vue -->
<script setup lang="ts">
import { computed } from 'vue'
interface Props {
variant?: 'primary' | 'secondary'
size?: 'sm' | 'md' | 'lg'
}
const props = withDefaults(defineProps<Props>(), {
variant: 'primary',
size: 'md'
})
const classes = computed(() => {
const base = 'rounded-lg font-medium transition-colors'
const variants = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300'
}
const sizes = {
sm: 'px-3 py-1.5 text-sm',
md: 'px-4 py-2',
lg: 'px-6 py-3 text-lg'
}
return `${base} ${variants[props.variant]} ${sizes[props.size]}`
})
</script>
<template>
<button :class="classes">
<slot />
</button>
</template>npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
**main.ts:**
```typescript
import { createApp } from 'vue'
import App from './App.vue'
import './assets/main.css'
createApp(App).mount('#app')组件示例:
vue
<!-- Button.vue -->
<script setup lang="ts">
import { computed } from 'vue'
interface Props {
variant?: 'primary' | 'secondary'
size?: 'sm' | 'md' | 'lg'
}
const props = withDefaults(defineProps<Props>(), {
variant: 'primary',
size: 'md'
})
const classes = computed(() => {
const base = 'rounded-lg font-medium transition-colors'
const variants = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300'
}
const sizes = {
sm: 'px-3 py-1.5 text-sm',
md: 'px-4 py-2',
lg: 'px-6 py-3 text-lg'
}
return `${base} ${variants[props.variant]} ${sizes[props.size]}`
})
</script>
<template>
<button :class="classes">
<slot />
</button>
</template>Component Patterns
组件模式
Layout Components
布局组件
Container
容器
jsx
function Container({ children, size = 'default' }) {
const sizes = {
sm: 'max-w-3xl',
default: 'max-w-7xl',
full: 'max-w-full'
};
return (
<div className={`container mx-auto px-4 sm:px-6 lg:px-8 ${sizes[size]}`}>
{children}
</div>
);
}jsx
function Container({ children, size = 'default' }) {
const sizes = {
sm: 'max-w-3xl',
default: 'max-w-7xl',
full: 'max-w-full'
};
return (
<div className={`container mx-auto px-4 sm:px-6 lg:px-8 ${sizes[size]}`}>
{children}
</div>
);
}Grid Layout
网格布局
jsx
function GridLayout({ children, cols = { default: 1, md: 2, lg: 3 } }) {
return (
<div className={`
grid
grid-cols-${cols.default}
md:grid-cols-${cols.md}
lg:grid-cols-${cols.lg}
gap-6
`}>
{children}
</div>
);
}jsx
function GridLayout({ children, cols = { default: 1, md: 2, lg: 3 } }) {
return (
<div className={`
grid
grid-cols-${cols.default}
md:grid-cols-${cols.md}
lg:grid-cols-${cols.lg}
gap-6
`}>
{children}
</div>
);
}Stack (Vertical Spacing)
堆叠(垂直间距)
jsx
function Stack({ children, spacing = 4 }) {
return (
<div className={`flex flex-col gap-${spacing}`}>
{children}
</div>
);
}jsx
function Stack({ children, spacing = 4 }) {
return (
<div className={`flex flex-col gap-${spacing}`}>
{children}
</div>
);
}UI Components
UI组件
Card
卡片
jsx
function Card({ title, description, image, footer }) {
return (
<div className="
bg-white dark:bg-gray-800
rounded-lg shadow-lg
overflow-hidden
transition-transform hover:scale-105
">
{image && (
<img
src={image}
alt={title}
className="w-full h-48 object-cover"
/>
)}
<div className="p-6">
<h3 className="text-xl font-bold mb-2 text-gray-900 dark:text-white">
{title}
</h3>
<p className="text-gray-600 dark:text-gray-400">
{description}
</p>
</div>
{footer && (
<div className="px-6 py-4 bg-gray-50 dark:bg-gray-700 border-t border-gray-200 dark:border-gray-600">
{footer}
</div>
)}
</div>
);
}jsx
function Card({ title, description, image, footer }) {
return (
<div className="
bg-white dark:bg-gray-800
rounded-lg shadow-lg
overflow-hidden
transition-transform hover:scale-105
">
{image && (
<img
src={image}
alt={title}
className="w-full h-48 object-cover"
/>
)}
<div className="p-6">
<h3 className="text-xl font-bold mb-2 text-gray-900 dark:text-white">
{title}
</h3>
<p className="text-gray-600 dark:text-gray-400">
{description}
</p>
</div>
{footer && (
<div className="px-6 py-4 bg-gray-50 dark:bg-gray-700 border-t border-gray-200 dark:border-gray-600">
{footer}
</div>
)}
</div>
);
}Modal
模态框
jsx
function Modal({ isOpen, onClose, title, children }) {
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 overflow-y-auto">
{/* Backdrop */}
<div
className="fixed inset-0 bg-black/50 backdrop-blur-sm"
onClick={onClose}
/>
{/* Modal */}
<div className="flex min-h-full items-center justify-center p-4">
<div className="
relative bg-white dark:bg-gray-800
rounded-lg shadow-xl
max-w-md w-full
p-6
animate-fade-in
">
<h2 className="text-2xl font-bold mb-4">
{title}
</h2>
<button
onClick={onClose}
className="absolute top-4 right-4 text-gray-400 hover:text-gray-600"
>
✕
</button>
{children}
</div>
</div>
</div>
);
}jsx
function Modal({ isOpen, onClose, title, children }) {
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 overflow-y-auto">
{/* 背景层 */}
<div
className="fixed inset-0 bg-black/50 backdrop-blur-sm"
onClick={onClose}
/>
{/* 模态框 */}
<div className="flex min-h-full items-center justify-center p-4">
<div className="
relative bg-white dark:bg-gray-800
rounded-lg shadow-xl
max-w-md w-full
p-6
animate-fade-in
">
<h2 className="text-2xl font-bold mb-4">
{title}
</h2>
<button
onClick={onClose}
className="absolute top-4 right-4 text-gray-400 hover:text-gray-600"
>
✕
</button>
{children}
</div>
</div>
</div>
);
}Form Input
表单输入框
jsx
function Input({ label, error, ...props }) {
return (
<div className="mb-4">
{label && (
<label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">
{label}
</label>
)}
<input
className={`
w-full px-4 py-2 rounded-lg
border ${error ? 'border-red-500' : 'border-gray-300'}
focus:outline-none focus:ring-2
${error ? 'focus:ring-red-500' : 'focus:ring-blue-500'}
bg-white dark:bg-gray-700
text-gray-900 dark:text-white
placeholder-gray-400
`}
{...props}
/>
{error && (
<p className="mt-1 text-sm text-red-500">{error}</p>
)}
</div>
);
}jsx
function Input({ label, error, ...props }) {
return (
<div className="mb-4">
{label && (
<label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">
{label}
</label>
)}
<input
className={`
w-full px-4 py-2 rounded-lg
border ${error ? 'border-red-500' : 'border-gray-300'}
focus:outline-none focus:ring-2
${error ? 'focus:ring-red-500' : 'focus:ring-blue-500'}
bg-white dark:bg-gray-700
text-gray-900 dark:text-white
placeholder-gray-400
`}
{...props}
/>
{error && (
<p className="mt-1 text-sm text-red-500">{error}</p>
)}
</div>
);
}Badge
徽章
jsx
function Badge({ children, variant = 'default', size = 'md' }) {
const variants = {
default: 'bg-gray-100 text-gray-800',
primary: 'bg-blue-100 text-blue-800',
success: 'bg-green-100 text-green-800',
warning: 'bg-yellow-100 text-yellow-800',
danger: 'bg-red-100 text-red-800',
};
const sizes = {
sm: 'text-xs px-2 py-0.5',
md: 'text-sm px-2.5 py-1',
lg: 'text-base px-3 py-1.5',
};
return (
<span className={`
inline-flex items-center
rounded-full font-medium
${variants[variant]}
${sizes[size]}
`}>
{children}
</span>
);
}jsx
function Badge({ children, variant = 'default', size = 'md' }) {
const variants = {
default: 'bg-gray-100 text-gray-800',
primary: 'bg-blue-100 text-blue-800',
success: 'bg-green-100 text-green-800',
warning: 'bg-yellow-100 text-yellow-800',
danger: 'bg-red-100 text-red-800',
};
const sizes = {
sm: 'text-xs px-2 py-0.5',
md: 'text-sm px-2.5 py-1',
lg: 'text-base px-3 py-1.5',
};
return (
<span className={`
inline-flex items-center
rounded-full font-medium
${variants[variant]}
${sizes[size]}
`}>
{children}
</span>
);
}Reference
参考
Common Utility Classes
常用实用工具类
Display & Positioning
显示与定位
display: block, inline-block, inline, flex, inline-flex, grid, inline-grid, hidden
position: static, fixed, absolute, relative, sticky
top/right/bottom/left: 0, auto, 1-96 (in 0.25rem increments)
z-index: z-0, z-10, z-20, z-30, z-40, z-50, z-autodisplay: block, inline-block, inline, flex, inline-flex, grid, inline-grid, hidden
position: static, fixed, absolute, relative, sticky
top/right/bottom/left: 0, auto, 1-96(以0.25rem为增量)
z-index: z-0, z-10, z-20, z-30, z-40, z-50, z-autoFlexbox & Grid
Flexbox与Grid
flex-direction: flex-row, flex-col, flex-row-reverse, flex-col-reverse
justify-content: justify-start, justify-center, justify-end, justify-between, justify-around
align-items: items-start, items-center, items-end, items-baseline, items-stretch
gap: gap-0 to gap-96 (in 0.25rem increments)
grid-cols: grid-cols-1 to grid-cols-12, grid-cols-noneflex-direction: flex-row, flex-col, flex-row-reverse, flex-col-reverse
justify-content: justify-start, justify-center, justify-end, justify-between, justify-around
align-items: items-start, items-center, items-end, items-baseline, items-stretch
gap: gap-0 至 gap-96(以0.25rem为增量)
grid-cols: grid-cols-1 至 grid-cols-12, grid-cols-noneSizing
尺寸
width: w-0 to w-96, w-auto, w-full, w-screen, w-1/2, w-1/3, w-2/3, etc.
height: h-0 to h-96, h-auto, h-full, h-screen
min/max-width: min-w-0, min-w-full, max-w-xs to max-w-7xl
min/max-height: min-h-0, min-h-full, max-h-screenwidth: w-0 至 w-96, w-auto, w-full, w-screen, w-1/2, w-1/3, w-2/3等
height: h-0 至 h-96, h-auto, h-full, h-screen
min/max-width: min-w-0, min-w-full, max-w-xs 至 max-w-7xl
min/max-height: min-h-0, min-h-full, max-h-screenSpacing (0.25rem = 4px increments)
间距(0.25rem = 4px增量)
padding: p-0 to p-96, px-*, py-*, pt-*, pr-*, pb-*, pl-*
margin: m-0 to m-96, mx-*, my-*, mt-*, mr-*, mb-*, ml-*, -m-*
space-between: space-x-*, space-y-*padding: p-0 至 p-96, px-*, py-*, pt-*, pr-*, pb-*, pl-*
margin: m-0 至 m-96, mx-*, my-*, mt-*, mr-*, mb-*, ml-*, -m-*
space-between: space-x-*, space-y-*Typography
排版
font-size: text-xs, text-sm, text-base, text-lg, text-xl to text-9xl
font-weight: font-thin to font-black (100-900)
text-align: text-left, text-center, text-right, text-justify
line-height: leading-none to leading-loose
letter-spacing: tracking-tighter to tracking-widestfont-size: text-xs, text-sm, text-base, text-lg, text-xl 至 text-9xl
font-weight: font-thin 至 font-black(100-900)
text-align: text-left, text-center, text-right, text-justify
line-height: leading-none 至 leading-loose
letter-spacing: tracking-tighter 至 tracking-widestColors (50-900 scale)
颜色(50-900刻度)
text-{color}-{shade}: text-gray-500, text-blue-600, text-red-700
bg-{color}-{shade}: bg-white, bg-gray-100, bg-blue-500
border-{color}-{shade}: border-gray-300, border-blue-500
Colors: slate, gray, zinc, neutral, stone, red, orange, amber, yellow, lime,
green, emerald, teal, cyan, sky, blue, indigo, violet, purple, fuchsia,
pink, rosetext-{color}-{shade}: text-gray-500, text-blue-600, text-red-700
bg-{color}-{shade}: bg-white, bg-gray-100, bg-blue-500
border-{color}-{shade}: border-gray-300, border-blue-500
颜色:slate, gray, zinc, neutral, stone, red, orange, amber, yellow, lime,
green, emerald, teal, cyan, sky, blue, indigo, violet, purple, fuchsia,
pink, roseBorders
边框
border-width: border, border-0, border-2, border-4, border-8
border-style: border-solid, border-dashed, border-dotted, border-double, border-none
border-radius: rounded-none, rounded-sm, rounded, rounded-lg, rounded-full
border-color: border-gray-300, etc.border-width: border, border-0, border-2, border-4, border-8
border-style: border-solid, border-dashed, border-dotted, border-double, border-none
border-radius: rounded-none, rounded-sm, rounded, rounded-lg, rounded-full
border-color: border-gray-300等Effects
效果
shadow: shadow-sm, shadow, shadow-md, shadow-lg, shadow-xl, shadow-2xl, shadow-none
opacity: opacity-0 to opacity-100 (in 5% increments)
blur: blur-none, blur-sm, blur, blur-lg, blur-xlshadow: shadow-sm, shadow, shadow-md, shadow-lg, shadow-xl, shadow-2xl, shadow-none
opacity: opacity-0 至 opacity-100(以5%为增量)
blur: blur-none, blur-sm, blur, blur-lg, blur-xlTransitions & Animations
过渡与动画
transition: transition-none, transition-all, transition, transition-colors, transition-opacity
duration: duration-75 to duration-1000 (ms)
timing: ease-linear, ease-in, ease-out, ease-in-out
animation: animate-none, animate-spin, animate-ping, animate-pulse, animate-bouncetransition: transition-none, transition-all, transition, transition-colors, transition-opacity
duration: duration-75 至 duration-1000(毫秒)
timing: ease-linear, ease-in, ease-out, ease-in-out
animation: animate-none, animate-spin, animate-ping, animate-pulse, animate-bounceResponsive Breakpoints
响应式断点
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)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)State Variants
状态变体
hover: &:hover
focus: &:focus
active: &:active
disabled: &:disabled
visited: &:visited (links)
checked: &:checked (inputs)
group-hover: .group:hover &
peer-focus: .peer:focus ~ &
first: &:first-child
last: &:last-child
odd: &:nth-child(odd)
even: &:nth-child(even)hover: &:hover
focus: &:focus
active: &:active
disabled: &:disabled
visited: &:visited(链接)
checked: &:checked(输入框)
group-hover: .group:hover &
peer-focus: .peer:focus ~ &
first: &:first-child
last: &:last-child
odd: &:nth-child(odd)
even: &:nth-child(even)Dark Mode
深色模式
dark: .dark &
dark:hover: .dark &:hover
dark:focus: .dark &:focusdark: .dark &
dark:hover: .dark &:hover
dark:focus: .dark &:focusBest Practices
最佳实践
Class Organization
类组织
jsx
// Group classes logically
<div className={`
// Layout
flex items-center justify-between
// Spacing
px-4 py-2 gap-2
// Typography
text-lg font-medium
// Colors
bg-white text-gray-900
// Borders & Effects
border border-gray-200 rounded-lg shadow-sm
// States
hover:bg-gray-50 focus:ring-2 focus:ring-blue-500
// Responsive
md:px-6 md:py-3
// Dark mode
dark:bg-gray-800 dark:text-white
`}>
Content
</div>jsx
// 按逻辑分组类
<div className={`
// 布局
flex items-center justify-between
// 间距
px-4 py-2 gap-2
// 排版
text-lg font-medium
// 颜色
bg-white text-gray-900
// 边框与效果
border border-gray-200 rounded-lg shadow-sm
// 状态
hover:bg-gray-50 focus:ring-2 focus:ring-blue-500
// 响应式
md:px-6 md:py-3
// 深色模式
dark:bg-gray-800 dark:text-white
`}>
内容
</div>Extracting Components
提取组件
jsx
// DON'T repeat complex class strings
<button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
Button 1
</button>
<button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
Button 2
</button>
// DO extract to component
function Button({ children }) {
return (
<button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
{children}
</button>
);
}jsx
// 不要重复复杂的类字符串
<button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
按钮1
</button>
<button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
按钮2
</button>
// 应该提取为组件
function Button({ children }) {
return (
<button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
{children}
</button>
);
}Using CSS Variables
使用CSS变量
javascript
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
primary: 'rgb(var(--color-primary) / <alpha-value>)',
secondary: 'rgb(var(--color-secondary) / <alpha-value>)',
},
},
},
}css
/* globals.css */
:root {
--color-primary: 59 130 246; /* RGB values for blue-500 */
--color-secondary: 139 92 246; /* RGB values for purple-500 */
}
.dark {
--color-primary: 96 165 250; /* Lighter blue for dark mode */
--color-secondary: 167 139 250; /* Lighter purple for dark mode */
}jsx
// Usage with opacity
<div className="bg-primary/50 text-primary">
50% opacity primary color
</div>javascript
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
primary: 'rgb(var(--color-primary) / <alpha-value>)',
secondary: 'rgb(var(--color-secondary) / <alpha-value>)',
},
},
},
}css
/* globals.css */
:root {
--color-primary: 59 130 246; /* blue-500的RGB值 */
--color-secondary: 139 92 246; /* purple-500的RGB值 */
}
.dark {
--color-primary: 96 165 250; /* 深色模式下的浅蓝色 */
--color-secondary: 167 139 250; /* 深色模式下的浅紫色 */
}jsx
// 带透明度的使用
<div className="bg-primary/50 text-primary">
50%透明度的主色调
</div>Avoiding Class Conflicts
避免类冲突
jsx
// DON'T use conflicting utilities
<div className="text-center text-left"> {/* text-left wins */}
// DO use conditional classes
<div className={isCenter ? 'text-center' : 'text-left'}>
// Or use clsx/cn utility
import { clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
function cn(...inputs) {
return twMerge(clsx(inputs))
}
<div className={cn(
'text-center',
isLeft && 'text-left' // Properly overrides
)}>jsx
// 不要使用冲突的工具类
<div className="text-center text-left"> {/* text-left会生效 */}
// 应该使用条件类
<div className={isCenter ? 'text-center' : 'text-left'}>
// 或使用clsx/cn工具
import { clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
function cn(...inputs) {
return twMerge(clsx(inputs))
}
<div className={cn(
'text-center',
isLeft && 'text-left' // 正确覆盖
)}>Troubleshooting
故障排除
Styles Not Applying
样式不生效
-
Check content paths in config:javascript
content: ['./src/**/*.{js,jsx,ts,tsx}'] -
Verify CSS imports:css
@tailwind base; @tailwind components; @tailwind utilities; -
Rebuild for dynamic classes:javascript
// DON'T - won't be detected <div className={`text-${color}-500`}> // DO - use safelist or complete class names <div className={color === 'red' ? 'text-red-500' : 'text-blue-500'}>
-
检查配置中的内容路径:javascript
content: ['./src/**/*.{js,jsx,ts,tsx}'] -
验证CSS导入:css
@tailwind base; @tailwind components; @tailwind utilities; -
动态类需要重新构建:javascript
// 错误 - 无法被检测到 <div className={`text-${color}-500`}> // 正确 - 使用安全列表或完整类名 <div className={color === 'red' ? 'text-red-500' : 'text-blue-500'}>
Build Size Issues
构建体积问题
- Optimize content configuration
- Remove unused plugins
- Use environment-specific configs
- Enable compression in production
- 优化内容配置
- 移除未使用的插件
- 使用环境特定的配置
- 生产环境启用压缩
Dark Mode Not Working
深色模式不生效
- Check darkMode setting in config
- Verify 'dark' class on html/body
- Test dark: variant syntax
- Check system preferences (media strategy)
- 检查配置中的darkMode设置
- 验证html/body上的'dark'类
- 测试dark:变体语法
- 检查系统偏好(media策略)
Resources
资源
- Official Docs: https://tailwindcss.com/docs
- Playground: https://play.tailwindcss.com
- Tailwind UI: https://tailwindui.com (Premium components)
- Headless UI: https://headlessui.com (Unstyled accessible components)
- Tailwind CLI: https://tailwindcss.com/docs/installation
- Class Variance Authority: https://cva.style (Type-safe variants)
- Prettier Plugin: https://github.com/tailwindlabs/prettier-plugin-tailwindcss
- 官方文档: https://tailwindcss.com/docs
- 在线游乐场: https://play.tailwindcss.com
- Tailwind UI: https://tailwindui.com(付费组件)
- Headless UI: https://headlessui.com(无样式的可访问组件)
- Tailwind CLI: https://tailwindcss.com/docs/installation
- Class Variance Authority: https://cva.style(类型安全的变体)
- Prettier插件: https://github.com/tailwindlabs/prettier-plugin-tailwindcss