Tailwind CSS 最佳实践

Tailwind CSS 开发的最佳实践和代码组织建议。


1. 代码组织

1.1 使用组件类

对于大量复用的样式,使用 @apply 创建组件类:

/* ✅ 好:使用组件类 */
.btn {
  @apply px-4 py-2 rounded-lg font-semibold transition-colors;
}
 
.btn-primary {
  @apply bg-blue-500 text-white hover:bg-blue-600;
}
 
.btn-secondary {
  @apply bg-gray-200 text-gray-700 hover:bg-gray-300;
}
<!-- 使用组件类 -->
<button class="btn btn-primary">主要按钮</button>
<button class="btn btn-secondary">次要按钮</button>

1.2 避免过度使用 @apply

不要过度使用 @apply,保持实用优先:

/* ❌ 不好:过度使用 @apply */
.card {
  @apply max-w-sm bg-white rounded-lg shadow-md overflow-hidden p-6;
}
 
/* ✅ 好:只在真正需要时使用 */
.card {
  @apply bg-white rounded-lg shadow-md;
}
<!-- 直接在 HTML 中使用工具类 -->
<div class="card max-w-sm overflow-hidden p-6">
  <!-- 内容 -->
</div>

2. 类名管理

2.1 使用 clsx 或 classnames

对于条件类名,使用工具库:

import clsx from 'clsx';
 
function Button({ primary, disabled, children }) {
  return (
    <button
      className={clsx(
        'px-4 py-2 rounded-lg font-semibold transition-colors',
        {
          'bg-blue-500 text-white hover:bg-blue-600': primary,
          'bg-gray-200 text-gray-700 hover:bg-gray-300': !primary,
          'opacity-50 cursor-not-allowed': disabled,
        }
      )}
    >
      {children}
    </button>
  );
}

2.2 避免字符串拼接

// ❌ 不好:字符串拼接
<div className={'text-' + size + ' font-' + weight}>
 
// ✅ 好:使用完整类名
<div className={clsx({
  'text-sm': size === 'sm',
  'text-base': size === 'base',
  'font-normal': weight === 'normal',
  'font-bold': weight === 'bold',
})}>

3. 响应式设计

3.1 移动优先

始终从移动端开始设计:

<!-- ✅ 好:移动优先 -->
<div class="text-sm md:text-base lg:text-lg">
 
<!-- ❌ 不好:桌面优先 -->
<div class="text-lg md:text-base sm:text-sm">

3.2 合理使用断点

不要为每个断点都设置样式:

<!-- ✅ 好:只在需要时使用 -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
 
<!-- ❌ 不好:过度使用断点 -->
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6">

4. 性能优化

4.1 正确配置 content

确保 Tailwind 能扫描到所有文件:

// ✅ 好:正确配置
module.exports = {
  content: [
    './src/**/*.{html,js,jsx,ts,tsx}',
    './public/index.html',
  ],
}
 
// ❌ 不好:配置不完整
module.exports = {
  content: ['./src/**/*.js'], // 缺少其他文件类型
}

4.2 避免动态类名

// ❌ 不好:动态类名(Tailwind 无法检测)
<div className={`text-${size}`}>
 
// ✅ 好:使用完整类名
<div className={size === 'sm' ? 'text-sm' : 'text-base'}>
 
// ✅ 更好:使用映射
const sizeMap = {
  sm: 'text-sm',
  base: 'text-base',
  lg: 'text-lg',
};
<div className={sizeMap[size]}>

4.3 使用生产构建

确保生产环境使用正确的构建配置:

# 生产构建
NODE_ENV=production npm run build

5. 可维护性

5.1 使用设计令牌

在配置中定义设计令牌:

module.exports = {
  theme: {
    extend: {
      colors: {
        primary: {
          50: '#eff6ff',
          500: '#3b82f6',
          900: '#1e3a8a',
        },
      },
      spacing: {
        '18': '4.5rem',
        '128': '32rem',
      },
    },
  },
}

5.2 创建工具类

对于常用的组合,创建工具类:

@layer utilities {
  .text-balance {
    text-wrap: balance;
  }
  
  .scrollbar-hide {
    -ms-overflow-style: none;
    scrollbar-width: none;
  }
  
  .scrollbar-hide::-webkit-scrollbar {
    display: none;
  }
}

6. 可访问性

6.1 语义化 HTML

使用语义化的 HTML 标签:

<!-- ✅ 好:语义化 -->
<nav class="bg-white shadow-md">
  <ul class="flex space-x-4">
    <li><a href="#">首页</a></li>
  </ul>
</nav>
 
<!-- ❌ 不好:div 滥用 -->
<div class="bg-white shadow-md">
  <div class="flex space-x-4">
    <div><a href="#">首页</a></div>
  </div>
</div>

6.2 焦点状态

确保所有交互元素都有焦点状态:

<!-- ✅ 好:有焦点状态 -->
<button class="px-4 py-2 bg-blue-500 text-white rounded-lg focus:ring-2 focus:ring-blue-500 focus:outline-none">
  按钮
</button>
 
<!-- ❌ 不好:缺少焦点状态 -->
<button class="px-4 py-2 bg-blue-500 text-white rounded-lg">
  按钮
</button>

6.3 颜色对比度

确保文字和背景有足够的对比度:

<!-- ✅ 好:足够的对比度 -->
<div class="bg-blue-500 text-white">
  文字
</div>
 
<!-- ❌ 不好:对比度不足 -->
<div class="bg-blue-100 text-blue-200">
  文字
</div>

7. 代码审查

7.1 审查清单

代码审查时检查:

  • 是否使用了正确的工具类
  • 响应式设计是否正确
  • 是否有不必要的类名
  • 是否遵循了移动优先
  • 是否有可访问性问题
  • 是否有性能问题

7.2 常见问题

问题 1:类名过长

<!-- ❌ 不好:类名过长 -->
<div class="flex items-center justify-between p-4 bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow cursor-pointer">
 
<!-- ✅ 好:使用组件类 -->
<div class="card-interactive">

问题 2:重复样式

<!-- ❌ 不好:重复样式 -->
<button class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">按钮 1</button>
<button class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">按钮 2</button>
 
<!-- ✅ 好:使用组件类 -->
<button class="btn btn-primary">按钮 1</button>
<button class="btn btn-primary">按钮 2</button>

8. 团队协作

8.1 统一配置

团队共享 tailwind.config.js

// tailwind.config.js
module.exports = {
  content: ['./src/**/*.{html,js,jsx,ts,tsx}'],
  theme: {
    extend: {
      // 团队统一的设计令牌
      colors: {
        brand: {
          primary: '#3b82f6',
          secondary: '#64748b',
        },
      },
    },
  },
  plugins: [],
}

8.2 代码规范

制定 Tailwind CSS 代码规范:

  • 类名顺序:布局 → 间距 → 颜色 → 文字 → 其他
  • 响应式:移动优先
  • 组件类:大量复用时才使用

9. 调试技巧

9.1 使用浏览器开发者工具

检查生成的 CSS:

  1. 打开浏览器开发者工具
  2. 检查元素
  3. 查看应用的样式
  4. 确认 Tailwind 类名是否正确应用

9.2 检查配置

确保 content 配置正确:

// 检查文件是否被扫描
console.log('Content paths:', require('./tailwind.config.js').content);

9.3 使用 Tailwind Play

Tailwind Play 中测试样式。


10. 下一步

现在你已经掌握了 Tailwind CSS 的最佳实践,可以:

  1. 查看 常见问题
  2. 学习 与框架集成
  3. 实践构建项目

相关链接

TailwindCSS 最佳实践 代码组织 性能优化