从厌恶到真香
Tailwind 的原子化 CSS 初看像是"把样式写进 HTML",但经过实践你会发现,它避免了 CSS 全局作用域的本质问题,让样式管理变得可预测且高效。
1. 思维转变
| 传统 CSS | Tailwind |
|---|---|
| 语义化类名 .btn-primary | 组合工具类 bg-blue-500 hover:bg-blue-600 |
| 全局样式污染 | 局部化(v4 中零配置) |
| CSS 文件无限增长 | 生产构建自动 Tree-shaking |
| 命名困难症 | 无需命名 |
2. 配置系统
// tailwind.config.js
export default {
content: ['./index.html', './src/**/*.{js,ts,jsx,tsx,vue}'],
theme: {
extend: {
colors: {
brand: {
DEFAULT: '#2563eb',
dark: '#1d4ed8',
light: '#60a5fa',
},
},
spacing: {
'18': '4.5rem',
'88': '22rem',
},
fontFamily: {
display: ['Inter', 'system-ui', 'sans-serif'],
},
},
},
plugins: [],
};
3. 组件实战
// React 组件
function PricingCard({ plan, price, features, isPopular }) {
return (
<div className={
'relative rounded-2xl p-8 shadow-lg transition-all duration-300 hover:scale-105 ' +
(isPopular ? 'ring-2 ring-brand bg-white' : 'bg-gray-50')
}>
{isPopular && (
<span className="absolute -top-3 left-1/2 -translate-x-1/2 rounded-full bg-brand px-4 py-1 text-xs font-semibold text-white">
最受欢迎
</span>
)}
<h3 className="text-xl font-bold text-gray-900">{plan}</h3>
<p className="mt-4">
<span className="text-4xl font-bold">¥{price}</span>
<span className="text-gray-500">/月</span>
</p>
<ul className="mt-6 space-y-3">
{features.map((f, i) => (
<li key={i} className="flex items-center gap-2 text-sm text-gray-600">
<CheckIcon className="h-4 w-4 text-green-500" />
{f}
</li>
))}
</ul>
<button className="mt-8 w-full rounded-lg bg-brand py-3 font-semibold text-white hover:bg-brand-dark transition-colors">
开始使用
</button>
</div>
);
}
4. 响应式与暗黑模式
<div class="
grid
grid-cols-1 sm:grid-cols-2 lg:grid-cols-3
gap-4 md:gap-6
px-4 sm:px-6 lg:px-8
bg-white dark:bg-gray-900
text-gray-900 dark:text-gray-100
">
{/* 响应式网格 + 暗黑模式 */}
</div>
总结
Tailwind CSS 的设计哲学是"约束带来效率"。放弃随意写 CSS 的自由,换来一致的设计语言、零运行时开销和极致的开发速度。这是现代前端工程化的正确选择。