一、什么是 Tailwind CSS?
Tailwind CSS 是一个功能类优先(Utility-First)的 CSS 框架。与传统 UI 框架不同,它没有预定义好的组件(如按钮、表单),而是提供了大量的原子类(如 text-xl
、bg-blue-500
、flex
等),开发者通过组合这些类快速构建自定义 UI。
二、Tailwind 的核心理念
✅ Utility-First
使用小而明确的样式类组合 UI 组件,而不是写样式或使用预设组件。
xml
<!-- 示例:一个红色按钮 -->
<button class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600">
点击我
</button>
✅ 组件复用
使用 @apply
或组件封装复用样式:
less
/* 在自定义 CSS 文件中 */
.btn {
@apply px-4 py-2 bg-blue-500 text-white rounded;
}
三、安装与配置
1. 安装 Tailwind(以 Vite 为例)
csharp
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
2. 配置 tailwind.config.js
css
module.exports = {
content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
theme: {
extend: {},
},
plugins: [],
}
3. 引入样式
在 src/index.css
中写入:
less
@tailwind base;
@tailwind components;
@tailwind utilities;
四、常用类名速查(精选)
功能 | 类名示例 | 说明 |
---|---|---|
布局 | flex grid block |
显示类型 |
尺寸 | w-64 h-screen |
宽高 |
间距 | m-4 p-6 mt-2 gap-4 |
外/内边距 |
排版 | text-xl font-bold text-center |
字体大小/粗细/对齐 |
颜色 | bg-blue-500 text-gray-700 |
背景/文字颜色 |
圆角 | rounded rounded-lg rounded-full |
圆角边框 |
边框 | border border-gray-300 border-2 |
边框样式 |
阴影 | shadow shadow-lg |
盒子阴影 |
状态 | hover:bg-blue-600 focus:outline-none |
交互状态样式 |
过渡 | transition duration-300 ease-in-out |
动画效果 |
响应式 | md:p-4 lg:flex |
媒体查询前缀 |
定位 | absolute top-0 left-0 |
绝对定位等 |
五、响应式设计
Tailwind 提供直观的断点系统:
断点 | 前缀 | 说明 |
---|---|---|
sm |
sm: |
≥ 640px |
md |
md: |
≥ 768px |
lg |
lg: |
≥ 1024px |
xl |
xl: |
≥ 1280px |
2xl |
2xl: |
≥ 1536px |
xml
<!-- 小屏文字小,大屏文字大 -->
<h1 class="text-lg md:text-2xl lg:text-4xl">响应式标题</h1>
六、组件实战案例
1. 卡片组件
ini
<div class="max-w-sm bg-white rounded-xl shadow-md overflow-hidden">
<img class="w-full h-48 object-cover" src="https://source.unsplash.com/random" alt="图片" />
<div class="p-6">
<h2 class="text-xl font-semibold text-gray-800">卡片标题</h2>
<p class="text-gray-600 mt-2">这是一个带阴影的卡片组件。</p>
<button class="mt-4 px-4 py-2 bg-indigo-500 text-white rounded hover:bg-indigo-600">了解更多</button>
</div>
</div>
七、主题扩展与自定义
在 tailwind.config.js
中添加自定义主题:
css
theme: {
extend: {
colors: {
primary: '#1e40af',
secondary: '#f59e0b',
},
spacing: {
'128': '32rem',
},
}
}
使用:
css
<div class="bg-primary text-white p-8">自定义颜色</div>
八、Dark Mode 支持
Tailwind 支持两种模式:media
(默认) 和 class
(更灵活)
java
// tailwind.config.js
module.exports = {
darkMode: 'class',
}
使用:
ini
<div class="bg-white text-black dark:bg-black dark:text-white">
暗黑模式内容
</div>
控制切换:
csharp
document.documentElement.classList.add('dark')
九、Tailwind 插件生态
@tailwindcss/forms
: 表单样式优化@tailwindcss/typography
: 富文本排版(如文章)@tailwindcss/aspect-ratio
: 固定宽高比
安装:
bash
npm install @tailwindcss/forms
配置:
css
plugins: [require('@tailwindcss/forms')]
十、实战技巧总结
- ✅ 使用
@apply
复用类 - ✅ 结合组件库(如 Headless UI)提升交互能力
- ✅ 搭配动画库如
framer-motion
可增强动画效果 - ✅ 浏览器插件推荐:Tailwind CSS IntelliSense(VSCode 插件)
十一、常见问题解答
Q: 为什么样式不生效?
A: 检查 tailwind.config.js
中 content
是否包含对应文件路径。
Q: 如何去除未使用的样式?
A: 使用 Tailwind 的构建模式自动 tree-shake(生产模式下自动完成)。