前言
还记得那些年在 HTML 和 CSS 文件之间反复切换的日子吗?为了给一个按钮加个内边距,你得先想个类名,再到 CSS 文件里写样式,最后还得担心这个类名会不会和其他地方冲突。传统的"语义化 CSS"开发模式,在项目规模扩大后往往会遇到命名冲突、样式膨胀、维护困难等问题。
Tailwind CSS 提供了一种全新的思路——"工具类优先" 的 CSS 框架。它让你不用离开 HTML,就能完成绝大部分样式编写。这个理念在刚接触时可能觉得"这不就是行内样式吗",但真正上手后,你会感受到它在开发效率和一致性上的巨大优势。
本文将带你从零开始,全面掌握 Tailwind CSS 的使用。
一、Tailwind CSS 是什么?
Tailwind CSS 是一个"工具类优先"的 CSS 框架。它不提供现成的组件(如按钮、卡片),而是提供大量单一职责的工具类(utility classes),你可以像搭积木一样组合它们来构建任何界面。
与传统 CSS 的对比
传统 CSS:语义化命名,样式与结构分离
<div class="card">
<h2 class="card-title">文章标题</h2>
<p class="card-content">这里是文章内容...</p>
</div>.card {
padding: 1.5rem;
background: white;
border-radius: 0.5rem;
box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
}
.card-title {
font-size: 1.25rem;
font-weight: 700;
margin-bottom: 0.5rem;
}
.card-content {
color: #4b5563;
line-height: 1.5;
}Tailwind CSS:工具类组合,样式写在 HTML 中
<div class="p-6 bg-white rounded-lg shadow-md">
<h2 class="text-xl font-bold mb-2">文章标题</h2>
<p class="text-gray-600 leading-relaxed">这里是文章内容...</p>
</div>核心优势
| 优势 | 说明 |
|---|---|
| 开发效率高 | 不用离开 HTML,不用想类名,不用切换文件 |
| 样式一致性 | 内置设计系统(间距、颜色、字体都遵循统一比例) |
| 无命名冲突 | 每个类只做一件事,不会互相干扰 |
| 体积可控 | 生产环境下会自动移除未使用的样式,最终 CSS 很小 |
| 响应式方便 | md:、lg: 等前缀直接在类名中控制断点 |
| 深色模式 | dark: 前缀轻松实现暗色主题 |
二、快速开始
方式一:CDN 引用(仅适合快速测试)
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2/dist/tailwind.min.css" rel="stylesheet">⚠️ CDN 版本功能受限,无法使用自定义主题、@apply 等高级功能,不推荐用于生产环境。方式二:npm 安装(推荐生产使用)
# 创建项目并进入
mkdir my-project && cd my-project
npm init -y
# 安装 Tailwind CSS
npm install -D tailwindcss
# 初始化配置文件
npx tailwindcss init方式三:Play CDN(在线体验)
<script src="https://cdn.tailwindcss.com"></script>适合在 CodePen 等在线编辑器快速尝试。
三、配置文件详解
tailwind.config.js 是 Tailwind 的核心配置文件:
/** @type {import('tailwindcss').Config} */
module.exports = {
// 扫描哪些文件中的类名
content: [
"./src/**/*.{html,js}",
"./*.php", // Typecho 主题可以扫描 PHP 文件
],
// 主题定制
theme: {
extend: {
colors: {
'primary': '#3b82f6',
'secondary': '#8b5cf6',
},
spacing: {
'18': '4.5rem',
},
fontFamily: {
'sans': ['Inter', 'system-ui', 'sans-serif'],
},
animation: {
'bounce-slow': 'bounce 2s infinite',
},
},
},
// 插件
plugins: [
require('@tailwindcss/forms'),
require('@tailwindcss/typography'),
],
}常用配置项说明
- content:告诉 Tailwind 扫描哪些文件,未在文件中出现的类名不会被生成到最终 CSS
- theme.extend:扩展默认主题,而不是覆盖
- plugins:官方插件,提供表单重置、文章排版等额外功能
四、核心用法
1. 使用 @tailwind 指令
创建 CSS 入口文件(如 src/input.css):
@tailwind base; /* 重置样式 */
@tailwind components; /* 组件类(可自定义) */
@tailwind utilities; /* 工具类 */然后运行构建命令:
npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch2. 基础样式(排版)
Tailwind 提供了 prose 类,让富文本内容自动获得良好的排版:
<article class="prose prose-lg prose-gray max-w-none">
<!-- 这里的内容会自动获得合适的字体、间距、颜色 -->
<h1>文章标题</h1>
<p>这是段落,会自动有合适的行高和边距。</p>
<ul>
<li>列表项 1</li>
<li>列表项 2</li>
</ul>
</article>3. 布局系统(Flex 和 Grid)
<!-- Flex 布局 -->
<div class="flex justify-between items-center">
<div>左侧内容</div>
<div>右侧内容</div>
</div>
<!-- Grid 布局:响应式卡片网格 -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<div class="card">卡片 1</div>
<div class="card">卡片 2</div>
<div class="card">卡片 3</div>
</div>4. 间距系统
Tailwind 的间距基于 4px 的倍数(0.25rem):
| 类名 | 值 | 类名 | 值 |
|---|---|---|---|
p-1 | 4px | p-4 | 16px |
p-2 | 8px | p-6 | 24px |
p-3 | 12px | p-8 | 32px |
<!-- 内边距 -->
<div class="p-4">内边距 16px</div>
<div class="px-6 py-3">水平 24px,垂直 12px</div>
<!-- 外边距 -->
<div class="m-2 mb-4 mt-6">不同方向不同值</div>
<!-- Gap 间距 -->
<div class="flex gap-4">间距 16px</div>5. 颜色系统
Tailwind 提供了丰富的调色板:
<!-- 文字颜色 -->
<p class="text-gray-900">深灰色文字</p>
<p class="text-blue-600">蓝色文字</p>
<p class="text-red-500 hover:text-red-700">悬停变深红</p>
<!-- 背景颜色 -->
<div class="bg-gray-100">浅灰背景</div>
<div class="bg-gradient-to-r from-blue-500 to-purple-600">
渐变背景
</div>
<!-- 边框颜色 -->
<input class="border border-gray-300 focus:border-blue-500">6. 响应式设计
使用断点前缀实现响应式:
| 前缀 | 最小宽度 | 说明 |
|---|---|---|
sm: | 640px | 手机横屏 |
md: | 768px | 平板 |
lg: | 1024px | 笔记本 |
xl: | 1280px | 桌面 |
2xl: | 1536px | 大屏 |
<!-- 手机上下排列,平板以上横向排列 -->
<div class="flex flex-col md:flex-row gap-4">
<div class="w-full md:w-1/2">左侧</div>
<div class="w-full md:w-1/2">右侧</div>
</div>
<!-- 字体大小随屏幕变化 -->
<h1 class="text-2xl md:text-4xl lg:text-5xl">
响应式标题
</h1>7. 状态变体(悬停、焦点等)
<!-- 悬停效果 -->
<button class="bg-blue-500 hover:bg-blue-700 transition">
悬停变色
</button>
<!-- 焦点效果 -->
<input class="focus:outline-none focus:ring-2 focus:ring-blue-500">
<!-- 组合使用 -->
<a class="text-gray-600 hover:text-blue-600 active:text-blue-800">
链接
</a>
<!-- 条件显示 -->
<div class="hidden md:block">
平板以上才显示
</div>8. 深色模式
<!-- 基础暗色模式 -->
<div class="bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100">
自动适配暗色/亮色主题
</div>
<!-- 暗色模式下的悬停 -->
<button class="bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600">
按钮
</button>需要在配置中开启暗色模式:
// tailwind.config.js
module.exports = {
darkMode: 'class', // 或 'media' 跟随系统
// ...
}9. 自定义组件类(@apply)
当重复使用相同的工具类组合时,可以用 @apply 提取:
/* 在 CSS 文件中 */
.btn-primary {
@apply px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition;
}
.card {
@apply bg-white rounded-lg shadow-md p-6;
}<!-- 使用时更简洁 -->
<button class="btn-primary">提交</button>
<div class="card">卡片内容</div>⚠️ 注意:过度使用 @apply 会失去 Tailwind 的核心优势,建议只在真正需要复用的组件上使用。五、构建配置
开发环境(监听变化)
npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch生产环境(压缩 + 清除未使用样式)
NODE_ENV=production npx tailwindcss -i ./src/input.css -o ./dist/output.css --minify配置 package.json 脚本
{
"scripts": {
"dev": "tailwindcss -i ./src/input.css -o ./dist/output.css --watch",
"build": "tailwindcss -i ./src/input.css -o ./dist/output.css --minify"
}
}使用时:
npm run dev # 开发
npm run build # 构建生产版本在 Typecho 主题中使用(具体示例)
假设你的 Typecho 主题目录是 /usr/themes/mytheme/:
- 创建构建脚本:
cd /usr/themes/mytheme/
npm init -y
npm install -D tailwindcss
npx tailwindcss init- 配置
tailwind.config.js:
module.exports = {
content: ["./**/*.php"], // 扫描所有主题模板
theme: {
extend: {},
},
plugins: [],
}- 创建
src/input.css:
@tailwind base;
@tailwind components;
@tailwind utilities;- 添加构建脚本到
package.json:
{
"scripts": {
"build": "tailwindcss -i ./src/input.css -o ./css/tailwind.css --minify"
}
}- 运行构建:
npm run build- 在主题
header.php中引入:
<link href="<?php $this->options->themeUrl('css/tailwind.css'); ?>" rel="stylesheet">- 在模板中使用 Tailwind 类名:
<!-- 文章列表 -->
<div class="max-w-4xl mx-auto px-4">
<?php while($this->next()): ?>
<article class="mb-8 p-6 bg-white rounded-lg shadow hover:shadow-md transition">
<h2 class="text-2xl font-bold mb-2">
<a href="<?php $this->permalink(); ?>" class="hover:text-blue-600">
<?php $this->title(); ?>
</a>
</h2>
<div class="text-gray-600 text-sm mb-4">
<?php $this->date('Y-m-d'); ?>
</div>
<div class="prose max-w-none">
<?php $this->excerpt(150); ?>
</div>
</article>
<?php endwhile; ?>
</div>六、常用类名速查表
布局类
| 类别 | 示例类名 |
|---|---|
| Display | block, inline-block, inline, flex, grid, hidden |
| Position | relative, absolute, fixed, sticky |
| Flex | flex-row, flex-col, justify-center, items-center |
| Grid | grid-cols-3, gap-4, col-span-2 |
尺寸类
| 类别 | 示例类名 |
|---|---|
| 宽度 | w-full, w-1/2, w-64, w-screen, min-w-0, max-w-lg |
| 高度 | h-auto, h-full, h-screen, min-h-screen |
间距类
| 类别 | 示例类名 |
|---|---|
| 内边距 | p-4, px-4, py-2, pt-4, pr-2, pb-4, pl-2 |
| 外边距 | m-4, mx-auto, my-2, mt-4, mr-2, mb-4, ml-2 |
| 间隙 | gap-4, gap-x-2, gap-y-4 |
文字类
| 类别 | 示例类名 |
|---|---|
| 字体大小 | text-xs, text-sm, text-base, text-lg, text-xl, text-2xl... |
| 字重 | font-light, font-normal, font-medium, font-bold |
| 文字颜色 | text-gray-500, text-red-600, text-blue-500 |
| 对齐 | text-left, text-center, text-right |
| 行高 | leading-none, leading-tight, leading-relaxed |
背景类
| 类别 | 示例类名 |
|---|---|
| 背景色 | bg-white, bg-gray-100, bg-blue-500 |
| 渐变色 | bg-gradient-to-r from-blue-500 to-purple-600 |
| 圆角 | rounded, rounded-lg, rounded-full |
| 阴影 | shadow-sm, shadow, shadow-md, shadow-lg, shadow-xl |
边框类
| 类别 | 示例类名 |
|---|---|
| 边框宽度 | border, border-2, border-t, border-b |
| 边框颜色 | border-gray-200, border-blue-500 |
| 边框圆角 | rounded-none, rounded-sm, rounded, rounded-md, rounded-lg, rounded-full |
效果类
| 类别 | 示例类名 |
|---|---|
| 透明度 | opacity-0, opacity-50, opacity-100 |
| 过渡 | transition, transition-all, duration-300, ease-in-out |
| 变换 | scale-105, rotate-90, translate-x-4 |
七、常见问题
1. Tailwind 和传统 CSS 能混用吗?
能。你可以在一个项目中同时使用 Tailwind 和自定义 CSS,Tailwind 的类名优先级较低(除非用 !important),不会冲突。这对于逐步迁移老项目非常友好。
<!-- 混合使用 -->
<div class="my-existing-class p-4 bg-white">
<!-- 自定义样式和 Tailwind 可以共存 -->
</div>2. 生产环境 CSS 体积很大怎么办?
Tailwind 的生产构建会自动移除未使用的样式。正确配置 content 字段后,最终生成的 CSS 通常只有 10KB 左右:
// tailwind.config.js
module.exports = {
content: [
"./src/**/*.{html,js}",
"./**/*.php", // Typecho 主题
],
}3. 如何添加自定义颜色?
在 tailwind.config.js 中配置:
module.exports = {
theme: {
extend: {
colors: {
'brand': '#3b82f6',
'brand-dark': '#1e40af',
}
}
}
}使用:
<div class="bg-brand text-white">自定义颜色</div>4. 如何调试 Tailwind 样式?
- 使用浏览器开发者工具查看元素的类名
- 添加插件:Tailwind CSS IntelliSense(VSCode)
- 使用
@tailwindcss/line-clamp处理多行文本截断
八、优缺点总结
优点
| 优点 | 说明 |
|---|---|
| ✅ 开发效率极高 | 不用起类名,不用切换文件 |
| ✅ 尺寸可控 | 生产构建自动 Tree Shaking |
| ✅ 一致性 | 内置设计系统,UI 不会失控 |
| ✅ 响应式简单 | 断点前缀,直观易懂 |
| ✅ 可维护性 | 不用担心样式冲突 |
| ✅ 社区活跃 | 插件丰富,生态成熟 |
缺点
| 缺点 | 解决方案 |
|---|---|
| ❌ HTML 类名臃肿 | 使用 @apply 提取重复组合 |
| ❌ 学习曲线 | 配合编辑器插件(自动补全) |
| ❌ 调试稍麻烦 | 熟能生巧,浏览器开发者工具可查看 |
| ❌ 构建步骤 | 需要配置构建流程(但一次配置,永久受益) |
九、学习资源
| 资源 | 链接/说明 |
|---|---|
| 官方文档 | https://tailwindcss.com/docs |
| 中文文档 | https://tailwindcss.cn/docs |
| 在线 Playground | https://play.tailwindcss.com |
| VSCode 插件 | Tailwind CSS IntelliSense |
| 常用类速查 | https://nerdfonts.com/cheat-sheet |
| 社区模板 | https://tailwindcomponents.com |
结语
Tailwind CSS 并非要完全取代传统 CSS,而是提供一种更高效的 UI 开发范式。它特别适合:
- 需要快速迭代的项目
- 团队多人协作,需要保持 UI 一致性
- 不想维护复杂 CSS 代码的场景
- 全栈开发者,不想在前端样式上花费太多时间
如果你厌倦了写 CSS 时的命名困难和样式冲突,不妨给 Tailwind CSS 一个机会。刚开始可能会有"类名太多记不住"的感觉,但配合编辑器插件和常用类速查表,不出三天就能得心应手。
暂无评论