Tailwind CSS 最佳实践
· CSS, Tailwind, 前端
Tailwind CSS 是一个实用优先的 CSS 框架,它提供了丰富的工具类,让你可以快速构建现代化的用户界面。
组件抽象
当同一个样式组合重复出现时,考虑将其提取为组件:
<!-- 重复的按钮样式 -->
<button class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
按钮
</button>
使用 @apply
/* styles.css */
.btn {
@apply px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors;
}
.btn-secondary {
@apply px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition-colors;
}
使用组件
// React 组件
function Button({ variant = 'primary', children }) {
const variants = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-200 text-gray-800 hover:bg-gray-300',
};
return (
<button className={`px-4 py-2 rounded-lg transition-colors ${variants[variant]}`}>
{children}
</button>
);
}
响应式设计
Tailwind 采用移动优先的响应式设计策略:
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<!-- 手机:1列,平板:2列,桌面:3列 -->
</div>
深色模式
启用深色模式:
// tailwind.config.js
module.exports = {
darkMode: 'class', // 或 'media'
}
使用深色模式类:
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
自适应深色模式的内容
</div>
自定义配置
扩展默认主题:
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
brand: {
50: '#f0f9ff',
500: '#0ea5e9',
900: '#0c4a6e',
},
},
fontFamily: {
sans: ['Inter', 'sans-serif'],
},
},
},
}
总结
Tailwind CSS 提供了一种高效的样式编写方式。通过合理使用组件抽象、响应式设计和深色模式,可以构建出美观且易维护的用户界面。