Tailwind CSS基础知识
# 一、Tailwind 是什么(核心思想)
Utility First(原子化 CSS)
- 不写(或极少写)传统 CSS
- 用类名直接描述样式
- 类名 = 样式语义,而不是业务语义
<button class="px-4 py-2 bg-blue-500 text-white rounded">
Button
</button>
1
2
3
2
3
等价于:
button {
padding: 8px 16px;
background: #3b82f6;
color: #fff;
border-radius: 6px;
}
1
2
3
4
5
6
2
3
4
5
6
# 二、核心基础分类(必须熟)
# 1️⃣ 布局(Layout)
# display
<div class="block"></div>
<div class="inline-block"></div>
<div class="flex"></div>
<div class="grid"></div>
1
2
3
4
2
3
4
# Flex(极其常用)
<div class="flex items-center justify-between">
1
flex-row / flex-colitems-center(交叉轴)justify-center / between / around(主轴)
# Grid
<div class="grid grid-cols-3 gap-4">
1
# 2️⃣ 间距(Spacing)
# margin / padding
<div class="m-4 p-2"></div>
<div class="mt-4 mb-2"></div>
<div class="px-4 py-2"></div>
1
2
3
2
3
记忆法:
m / pt r b l x y- 数字 =
4px * n
# 3️⃣ 尺寸(Size)
<div class="w-32 h-16"></div>
<div class="w-full h-screen"></div>
<div class="max-w-md"></div>
1
2
3
2
3
常用:
w-fullh-screenmin-h-screenmax-w-xl
# 4️⃣ 文字(Typography)
<p class="text-sm text-gray-600"></p>
<p class="text-lg font-bold"></p>
<p class="leading-relaxed tracking-wide"></p>
1
2
3
2
3
text-xs ~ text-2xlfont-light / normal / medium / boldtext-left / center / right
# 5️⃣ 颜色(Color)
<div class="bg-red-500 text-white"></div>
<div class="border border-gray-200"></div>
1
2
2
结构统一:
{property}-{color}-{level}
1
如:
bg-blue-500text-gray-700border-zinc-200
# 6️⃣ 边框 & 圆角 & 阴影
<div class="border rounded-lg shadow-md"></div>
1
rounded / rounded-md / rounded-fullshadow / shadow-lg
# 7️⃣ 定位(Position)
<div class="relative">
<span class="absolute top-0 right-0"></span>
</div>
1
2
3
2
3
relativeabsolutefixedsticky
# 三、响应式(Tailwind 很强)
# 断点前缀
sm ≥640px
md ≥768px
lg ≥1024px
xl ≥1280px
2xl ≥1536px
1
2
3
4
5
2
3
4
5
# 用法
<div class="text-sm md:text-base lg:text-lg"></div>
1
📌 移动端优先
# 四、状态修饰(非常重要)
# hover / focus / active
<button class="bg-blue-500 hover:bg-blue-600 focus:ring-2">
1
# group(父子联动)
<div class="group">
<span class="group-hover:text-red-500"></span>
</div>
1
2
3
2
3
# 五、暗黑模式(Dark Mode)
<div class="bg-white dark:bg-gray-900 text-black dark:text-white">
1
tailwind.config.js:
darkMode: 'class'
1
# 六、常见组合套路(实战)
# ✅ 卡片
<div class="p-4 rounded-lg shadow bg-white">
1
# ✅ 居中
<div class="flex items-center justify-center h-screen">
1
# ✅ 按钮
<button
class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition"
>
1
2
3
2
3
# 七、Tailwind 在 Vue 中的使用要点
# 1️⃣ 动态 class
<div :class="isActive ? 'bg-blue-500' : 'bg-gray-300'"></div>
1
或:
<div :class="['p-4', isActive && 'bg-blue-500']"></div>
1
# 2️⃣ 避免 purge 掉动态类
❌
`bg-${color}-500`
1
✅
const map = {
red: 'bg-red-500',
blue: 'bg-blue-500'
}
1
2
3
4
2
3
4
# 八、什么时候不用 Tailwind?
❌
- 超复杂动画(建议配合 CSS / GSAP)
- 大量重复组件却不抽象
- 对 class 极度敏感的设计师协作
✅
- 后台 / 中台
- 组件库
- 快速原型
- H5 页面
# 九、学习顺序建议(给你)
- Spacing / Flex / Typography
- Responsive + 状态修饰
- Dark Mode
- Tailwind Config(theme / extend)
- 组件抽象(@apply / 组件化)
上次更新: 2025/12/26, 01:42:33