Tailwind CSS 实战技巧:从入门到精通
4 min read
#Tailwind CSS#CSS#前端#设计系统
Tailwind CSS 实战技巧:从入门到精通
Tailwind CSS 已经成为现代前端开发中不可或缺的工具。今天我将分享一些实战技巧,帮助你更高效地使用 Tailwind。
为什么选择 Tailwind?
- 原子化 CSS:每个类名只做一件事
- 高度可定制:通过配置文件控制设计系统
- 开发效率高:无需离开 HTML 编写样式
- 生产体积小:PurgeCSS 自动移除未使用的样式
基础配置
tailwind.config.js
module.exports = {
content: ['./src/**/*.{js,ts,jsx,tsx}'],
theme: {
extend: {
colors: {
primary: {
50: '#f0f9ff',
500: '#0ea5e9',
900: '#0c4a6e',
},
},
fontFamily: {
sans: ['Inter', 'sans-serif'],
},
},
},
plugins: [],
}
高级技巧
1. 使用 @apply 抽象重复样式
@layer components {
.btn-primary {
@apply px-4 py-2 bg-primary-500 text-white rounded-lg
hover:bg-primary-600 transition-colors;
}
}
2. 自定义工具类
// tailwind.config.js
module.exports = {
theme: {
extend: {
spacing: {
'128': '32rem',
'144': '36rem',
}
}
}
}
3. 响应式设计
<div className="w-full md:w-1/2 lg:w-1/3 xl:w-1/4">
Responsive Width
</div>
4. 暗色模式
<div className="bg-white dark:bg-gray-900 text-black dark:text-white">
Dark Mode Support
</div>
组件化最佳实践
使用 clsx 组合类名
import clsx from 'clsx'
function Button({ variant, size, className, ...props }) {
return (
<button
className={clsx(
'rounded-lg font-semibold transition-colors',
{
'bg-blue-500 text-white': variant === 'primary',
'bg-gray-200 text-gray-900': variant === 'secondary',
},
{
'px-3 py-1 text-sm': size === 'small',
'px-4 py-2': size === 'medium',
'px-6 py-3 text-lg': size === 'large',
},
className
)}
{...props}
/>
)
}
CVA (Class Variance Authority)
import { cva } from 'class-variance-authority'
const button = cva('button-base', {
variants: {
intent: {
primary: 'bg-blue-500 text-white',
secondary: 'bg-gray-200 text-gray-900',
},
size: {
small: 'text-sm px-3 py-1',
medium: 'text-base px-4 py-2',
},
},
defaultVariants: {
intent: 'primary',
size: 'medium',
},
})
性能优化
1. 配置 PurgeCSS
module.exports = {
content: [
'./src/**/*.{js,jsx,ts,tsx}',
'./public/index.html',
],
}
2. 使用 JIT 模式
JIT (Just-In-Time) 模式在开发时只生成你实际使用的样式:
module.exports = {
mode: 'jit',
// ...
}
3. 优化构建体积
# 生产构建时自动优化
npm run build
常见陷阱
❌ 避免动态类名
// 不好 - 不会被 PurgeCSS 识别
<div className={`text-${color}-500`}>Bad</div>
// 好 - 使用完整类名
<div className={color === 'blue' ? 'text-blue-500' : 'text-red-500'}>Good</div>
✅ 使用 safelist
如果必须使用动态类名:
module.exports = {
safelist: [
'text-blue-500',
'text-red-500',
'text-green-500',
],
}
实用插件推荐
- @tailwindcss/forms - 表单样式
- @tailwindcss/typography - 排版
- @tailwindcss/aspect-ratio - 宽高比
- tailwindcss-animate - 动画工具
总结
Tailwind CSS 的强大之处在于它的灵活性和可扩展性。掌握这些技巧后,你可以构建出既美观又高性能的 Web 应用。
Happy Styling! 🎨