Tailwind CSS:从“原子地狱”到“真香”——一份避免过度设计的工程师指南

目标:用最少字数,让你决定“用还是不用”,并提供“够用就好”的最佳实践。


1. 一句话省流

  • 三页以内管理后台 → 直接 Bootstrap,别上 Tailwind。
  • 需要像素级还原 / 多主题 / 组件库解耦 → Tailwind 值得,但务必“砍配置 + 白名单 + @apply”,否则就是原子地狱。

2. 与 Bootstrap 的本质差异(代码说话)

场景Bootstrap 5Tailwind(按需子集)
自定义品牌色$primary 并重新编译源码tailwind.config.js 里加一行 primary: colors.indigo
头像负间距 + 描边写自定义 CSS-ml-4 ring-4 ring-white(原子一步到位)
生产体积最低 38 kB(grid 仅)4 kB(gzip,白名单配置)
暗黑模式换整套 bootstrap-dark.css同一行 class:dark:bg-gray-900
对话框逻辑依赖 jQuery/Popper,样式耦合用 Headless UI,样式 100% 自定义

3. 过度设计现场

<!-- 反面教材:原子地狱 -->
<button class="relative inline-flex items-center justify-center px-4 py-2 md:px-6 md:py-3 text-sm md:text-base font-semibold text-white bg-indigo-600 border border-transparent rounded-md shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed ...">
  提交
</button>

维护者想改一个字号,得在 200 个文件里全局搜索替换。


4. “够用就好”四步法

① 砍配置(只留 3 档断点 + 限定颜色 & 间距)

// tailwind.config.js
module.exports = {
  content: ['./src/**/*.{html,js}'],
  theme: {
    screens: { sm: '640px', md: '768px', lg: '1024px' },
    colors: ({ colors }) => ({
      transparent: colors.transparent,
      white: '#fff',
      gray: colors.slate,
      primary: colors.indigo,
    }),
    extend: {
      spacing: { 0: '0', 2: '0.5rem', 4: '1rem', 6: '1.5rem', 8: '2rem', 12: '3rem' },
    },
  },
  plugins: [],
}

② 白名单类名(最多 20 个)

布局:flex / grid / block / hidden / md:flex
间距:p/m-0/2/4/6/8
字号:text-sm/base/lg/xl/2xl
颜色:text-gray-600/900 bg-white primary-500
圆角:rounded / rounded-md
阴影:shadow / shadow-md
交互:hover:bg-primary-600 disabled:opacity-50

③ 超了就用 @apply

@layer components {
  .btn {
    @apply inline-flex items-center px-4 py-2 rounded bg-primary-500 text-white hover:bg-primary-600 disabled:opacity-50;
  }
  .card {
    @apply bg-white rounded-md shadow p-4;
  }
}

④ 把原子关进组件(React 示例)

export function Button({ primary, children }) {
  const base = 'btn';          // 已经 @apply 过
  return <button className={base}>{children}</button>;
}

业务层再看不到长串 class。


5 体积对比实测

项目体积(gzip)
Bootstrap 按需(grid + reboot + utilities)38 kB
Tailwind(白名单子集)4 kB
差异-89%

6 何时坚决不用

  • 页面数 < 5,0 设计师,生命周期 < 3 个月。
  • 后端同学兼职维护,对“class 长字符串”零容忍。
  • 无构建流程,直接扔静态 HTML。

7 结论

Tailwind 是不是“新 Bootstrap”?
—— 思想相似,粒度、可编程性、主题方案完全不同。
值不值得上?
—— 先砍配置、再锁白名单、及时 @apply,就能让它退化成“带设计变量的 Bootstrap”,避免原子地狱;否则,宁可继续 Bootstrap 一把梭。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值