返回列表

Tailwind CSS 最佳实践

6 分钟阅读

Tailwind CSS 最佳实践

项目配置

1. 自定义配置

// tailwind.config.js
module.exports = {
  content: [
    './app/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    extend: {
      colors: {
        primary: '#667eea',
        secondary: '#764ba2',
      },
    },
  },
  plugins: [
    require('@tailwindcss/typography'),
  ],
}

2. 组件化思维

按钮组件

interface ButtonProps {
  variant?: 'primary' | 'secondary' | 'outline'
  size?: 'sm' | 'md' | 'lg'
  children: React.ReactNode
}

const Button: React.FC<ButtonProps> = ({ 
  variant = 'primary', 
  size = 'md', 
  children 
}) => {
  const baseClasses = 'font-medium rounded-lg transition-colors'
  const variantClasses = {
    primary: 'bg-primary text-white hover:bg-primary/90',
    secondary: 'bg-secondary text-white hover:bg-secondary/80',
    outline: 'border border-primary text-primary hover:bg-primary/10',
  }
  const sizeClasses = {
    sm: 'px-3 py-1.5 text-sm',
    md: 'px-4 py-2 text-base',
    lg: 'px-6 py-3 text-lg',
  }
  
  return (
    <button className={`${baseClasses} ${variantClasses[variant]} ${sizeClasses[size]}`}>
      {children}
    </button>
  )
}

响应式设计

1. 移动优先

<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
  {/* 内容 */}
</div>

2. 断点使用

  • sm: 640px
  • md: 768px
  • lg: 1024px
  • xl: 1280px
  • 2xl: 1536px

性能优化

1. 使用 JIT 模式

Tailwind CSS v3 默认启用 JIT 模式,只生成用到的类。

2. 避免重复样式

使用 @apply 创建组件类:

@layer components {
  .btn-primary {
    @apply bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90;
  }
}

3. 深色模式支持

<div className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
  支持深色模式的内容
</div>

实用技巧

1. 任意值支持

<div className="w-[123px] h-[456px]">自定义尺寸</div>

2. 状态变体

<button className="hover:bg-blue-500 focus:outline-none focus:ring-2 active:bg-blue-700">
  交互状态
</button>

3. 组合使用

<div className="flex items-center justify-between p-4 bg-white rounded-lg shadow-md border border-gray-200">
  组合样式
</div>