我在 3 个项目中使用 Tailwind CSS 后的 8 条经验
Tailwind CSS 争议很大。有人说它"污染 HTML",有人说它"提升效率 10 倍"。我在 3 个生产项目中使用后,总结了一些实用经验。
1. 不要怕长 className
TSX
// 很多人觉得这样丑
<button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
提交
</button>
// 但它的好处是:看代码就知道样式,不需要在文件间跳转
// 解决"太长"的办法:抽成组件
function PrimaryButton({ children, ...props }: ButtonProps) {
return (
<button
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
{...props}
>
{children}
</button>
)
}2. 善用 @apply 但别滥用
CSS
/* 好的用法 - 重复出现的按钮样式 */
@layer components {
.btn-primary {
@apply px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors;
}
.btn-secondary {
@apply px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition-colors;
}
}
/* 坏的用法 - 单个元素也用 @apply,不如直接用 className */
.bad-example {
@apply flex items-center justify-between p-4;
}3. 颜色系统
JS
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
brand: {
50: '#eff6ff',
500: '#3b82f6',
600: '#2563eb',
700: '#1d4ed8',
}
}
}
}
}使用时:bg-brand-600,语义清晰。
4. 响应式从移动端开始
TSX
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{/* 移动端 1 列,平板 2 列,桌面 3 列 */}
</div>5. 用 cn() 处理条件样式
TYPESCRIPT
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
// 使用
<button className={cn(
'px-4 py-2 rounded-lg',
variant === 'primary' && 'bg-blue-600 text-white',
disabled && 'opacity-50 cursor-not-allowed'
)}>
提交
</button>6. 不要和 inline style 混用
TSX
// 不要这样
<div className="flex items-center" style={{ gap: '12px' }}>
// gap 有对应的 Tailwind 类
<div className="flex items-center gap-3">7. 性能考虑
生产构建时,Tailwind 会自动 purging 未使用的样式。但要注意:
JS
// tailwind.config.js
module.exports = {
content: [
"./src/**/*.{js,ts,jsx,tsx}", // 确保包含所有文件
],
}8. 团队规范
JSON
// .vscode/settings.json
{
"tailwindCSS.experimental.classRegex": [
["cn\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"]
]
}安装 Tailwind CSS IntelliSense 插件,自动补全类名。
总结
Tailwind 适合:
- 组件化开发(React/Vue)
- 快速原型
- 团队协作(样式规范统一)
不适合:
- 传统多页面网站
- 大量自定义样式
- 不喜欢工具类 CSS 的团队
读者评论 4