以下是为初学者准备的 Tailwind CSS 详细使用教程,从安装到核心功能逐步解析:
一、什么是 Tailwind CSS?
Tailwind 是一个 实用类优先(Utility-First) 的 CSS 框架,通过组合预定义的类名快速构建 UI,无需手写 CSS。例如,直接使用 bg-blue-500 text-white p-4 rounded 类名组合即可创建一个蓝色按钮。
二、安装与配置
1. 通过 CDN 快速体验(适合简单项目)
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<!-- 直接使用 Tailwind 类名 -->
<button class="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600">
点击我
</button>
</body>
</html>
2. 通过 npm 安装(推荐正式项目)
npm install -D tailwindcss
npx tailwindcss init # 生成配置文件 tailwind.config.js
3. 集成到项目构建流程
在 CSS 入口文件(如 src/input.css)中引入: ``css @tailwind base; /* 基础样式 */ @tailwind components; /* 组件类 */ @tailwind utilities; /* 实用类 */ ``
三、基础用法
示例:创建一个卡片组件
<div class="max-w-sm rounded-lg shadow-lg bg-white p-6">
<h3 class="text-xl font-bold text-gray-800 mb-2">卡片标题</h3>
<p class="text-gray-600">这是一个使用 Tailwind 构建的卡片组件,支持响应式和悬停效果。</p>
<button class="mt-4 bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600">
了解更多
</button>
</div>
四、核心功能详解
1. 实用类命名规则
- 属性缩写:
p-4→padding: 1rem,mt-2→margin-top: 0.5rem - 数值缩放:间距、字体大小等按比例缩放(如
0.25rem为1单位) - 状态修饰:
hover:bg-blue-600(悬停)、focus:ring-2(焦点)
2. 响应式设计
使用断点前缀(如 md:、lg:)适配不同屏幕:
<div class="text-center md:text-left lg:flex">
<!-- 小屏居中,中屏左对齐,大屏 Flex 布局 -->
</div>
3. 自定义主题
修改 tailwind.config.js 扩展颜色、字体等:
module.exports = {
theme: {
extend: {
colors: {
primary: '#3B82F6', // 添加自定义颜色
}
}
}
}
4. 深色模式
通过 dark: 前缀切换主题:
<div class="bg-white dark:bg-gray-800">
<p class="text-gray-900 dark:text-white">深色模式文本</p>
</div>
五、进阶技巧
1. 提取复用样式(@apply)
将常用类组合为 CSS 类(在 CSS 文件中): ``css .btn-primary { @apply px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600; } `` #### 2. 使用 JIT 模式(即时编译) 在 tailwind.config.js 中启用: ``js module.exports = { mode: 'jit', // 显著提升编译速度,按需生成样式 purge: ['./**/*.html'], } `` #### 3. 结合插件扩展 安装官方插件(如动画、排版): ``bash npm install @tailwindcss/typography @tailwindcss/forms `` 配置: ``js plugins: [require('@tailwindcss/typography'), require('@tailwindcss/forms')] ``
六、优劣分析
✅ 优点:
- 开发速度快,无需上下文切换(HTML/CSS 分离)
- 设计系统约束统一,避免样式膨胀
- 响应式与状态处理便捷
⚠️ 缺点:
- HTML 类名较多(可通过组件化解决)
- 学习成本(需记忆类名或依赖文档)
七、学习资源
- 官方文档:tailwindcss.com/docs
- 交互式教程:Tailwind Play
- 视频课程:YouTube 搜索 "Tailwind CSS Tutorial"
- UI 模板:Tailwind Components
快速体验建议:
- 打开 Tailwind Play
- 粘贴以下代码尝试修改:
<div class="p-8">
<button class="bg-gradient-to-r from-purple-500 to-pink-500 text-white px-6 py-3 rounded-full shadow-lg hover:scale-105 transition-transform">
悬浮放大效果
</button>
</div>