Tailwind CSS 简介
Tailwind CSS 是一个功能类优先的 CSS 框架,它提供了大量的预定义类,让你可以快速构建用户界面。与其他框架不同,Tailwind 不提供预构建的组件,而是提供低级的实用工具类。
基础使用
快速开始
安装 Tailwind CSS:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
配置 tailwind.config.js:
module.exports = {
content: ['./src/**/*.{html,js,jsx,ts,tsx,astro}'],
theme: {
extend: {},
},
plugins: [],
}
响应式设计
Tailwind 使用移动优先的响应式设计:
<div class="w-full md:w-1/2 lg:w-1/3">
<!-- 在不同屏幕尺寸下占据不同宽度 -->
</div>
响应式断点:
sm: 640pxmd: 768pxlg: 1024pxxl: 1280px2xl: 1536px
实用技巧
1. 使用 @apply 提取常用样式
如果你有重复使用的样式组合,可以使用 @apply 提取:
.btn-primary {
@apply px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors;
}
2. 自定义主题扩展
在 tailwind.config.js 中扩展主题:
module.exports = {
theme: {
extend: {
colors: {
primary: '#3b82f6',
secondary: '#10b981',
},
fontFamily: {
sans: ['Inter', 'sans-serif'],
},
},
},
}
3. 使用任意值
Tailwind 允许你使用方括号来使用任意值:
<div class="w-[320px] h-[180px] top-[117px]">
<!-- 使用自定义值 -->
</div>
4. 使用 group 和 group-hover
当需要基于父元素的状态来控制子元素的样式时:
<div class="group">
<p class="opacity-0 group-hover:opacity-100 transition-opacity">
鼠标悬停时显示
</p>
</div>
5. 使用 peer 和 peer-*
基于兄弟元素的状态:
<div>
<input type="checkbox" class="peer" />
<label class="peer-checked:bg-blue-500">
勾选时改变背景色
</label>
</div>
6. 动态类名与重要标记
使用 !important:
<div class="!bg-red-500">
<!-- 强制应用背景色 -->
</div>
7. 使用 data-* 属性
基于 data 属性的样式:
<div class="data-[open]:bg-blue-500">
<!-- 当有 data-open 属性时应用背景色 -->
</div>
高级技巧
1. 使用插件扩展功能
Tailwind 有很多官方和社区插件:
// tailwind.config.js
module.exports = {
plugins: [
require('@tailwindcss/forms'),
require('@tailwindcss/typography'),
require('@tailwindcss/aspect-ratio'),
],
}
2. 自定义变体
添加自定义的变体:
// tailwind.config.js
module.exports = {
theme: {
extend: {
variants: {
display: ['group-hover'],
},
},
},
}
3. 使用 JIT 模式
Tailwind CSS v3 默认使用 JIT(Just-In-Time)模式,它可以:
- 实时生成样式
- 更小的 CSS 体积
- 支持任意值
// tailwind.config.js
module.exports = {
mode: 'jit',
// ...
}
最佳实践
1. 组件抽象
对于常用的 UI 模式,考虑创建组件:
---
interface Props {
variant?: 'primary' | 'secondary';
size?: 'sm' | 'md' | 'lg';
}
const { variant = 'primary', size = 'md' } = Astro.props;
const styles = {
primary: 'bg-blue-500 hover:bg-blue-600',
secondary: 'bg-gray-500 hover:bg-gray-600',
sm: 'px-3 py-1.5 text-sm',
md: 'px-4 py-2',
lg: 'px-6 py-3 text-lg',
};
---
<button class={`rounded-md text-white transition-colors ${styles[variant]} ${styles[size]}`}>
<slot />
</button>
2. 保持可读性
当类名过多时,考虑换行:
<button
class="
px-4 py-2
bg-blue-500 hover:bg-blue-600
text-white rounded-md
transition-colors
disabled:opacity-50
"
>
按钮
</button>
3. 使用 PurgeCSS 精简样式
在生产环境中,只包含使用的样式:
// tailwind.config.js
module.exports = {
purge: ['./src/**/*.{astro,html,js,jsx,ts,tsx}'],
// ...
}
总结
Tailwind CSS 是一个强大而灵活的工具,掌握这些技巧可以帮助你更高效地构建用户界面。
关键要点:
- 🎨 使用实用类快速构建 UI
- 📱 利用响应式类实现移动优先设计
- 🔧 通过插件和主题扩展定制功能
- 🧩 将常用样式抽象为组件
- 🚀 使用 JIT 模式获得更好的性能
开始在你的项目中使用 Tailwind CSS,享受快速开发的乐趣吧!