Tailwind CSS 实战:从抵触到真香

Tailwind CSS 实战:从抵触到真香

初遇 Tailwind CSS 时,我和很多人一样抵触——在 className 里写一堆工具类,这和内联样式有什么区别?但随着深入使用,我逐渐理解了它的设计哲学:约束带来一致性,原子类组合出无限可能。

自定义设计系统是 Tailwind 在大型项目中成功的关键:

示意图
示意图
// tailwind.config.ts
import type { Config } from "tailwindcss";

export default {
    theme: {
        extend: {
            colors: {
                brand: {
                    50: "#eff6ff",
                    500: "#3b82f6",
                    900: "#1e3a8a",
                },
            },
            spacing: {
                18: "4.5rem",
                88: "22rem",
            },
            fontSize: {
                "2xs": ["0.625rem", { lineHeight: "0.875rem" }],
            },
        },
    },
} satisfies Config;

组件封装避免 className 重复:

// Button 组件
const buttonVariants = cva("inline-flex items-center rounded-lg font-medium", {
    variants: {
        intent: {
            primary: "bg-brand-500 text-white hover:bg-brand-600",
            secondary: "bg-gray-100 text-gray-700 hover:bg-gray-200",
            danger: "bg-red-500 text-white hover:bg-red-600",
        },
        size: {
            sm: "px-3 py-1.5 text-sm",
            md: "px-4 py-2 text-base",
            lg: "px-6 py-3 text-lg",
        },
    },
    defaultVariants: {
        intent: "primary",
        size: "md",
    },
});

在性能方面,Tailwind 的 JIT 引擎只生成使用到的工具类,生产构建的 CSS 通常不超过 10KB。配合 Prettier 插件自动排序 className,开发体验已经非常流畅。我们团队从 SASS 迁移到 Tailwind 后,样式代码量减少了 40%,UI 一致性显著提升。