1.安装步骤
# 在你的 Vite 项目中安装 Tailwind CSS 及其依赖
npm install -D tailwindcss postcss autoprefixer
# 生成 Tailwind CSS 和 PostCSS 配置文件
npx tailwindcss init -p
2. 配置文件设置
/** @type {import('tailwindcss').Config} */
export default {
// 指定要处理的文件
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}", // 处理 src 目录下所有的相关文件
],
theme: {
extend: {
// 在这里扩展 Tailwind 的默认配置
colors: {
'custom-blue': '#1234567', // 自定义颜色
},
spacing: {
'128': '32rem', // 自定义间距
},
// 更多自定义配置...
},
},
plugins: [
// 这里可以添加 Tailwind 插件
],
}
3.在主 CSS 文件中添加 Tailwind 指令
/* 导入 Tailwind 的基础样式 */
@tailwind base;
/* 导入组件样式 */
@tailwind components;
/* 导入功能类 */
@tailwind utilities;
/* 自定义 CSS 类 */
@layer components {
.btn-primary {
@apply px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600;
}
}
4.使用示例
<template>
<!-- 基础样式使用 -->
<div class="flex min-h-screen bg-gray-100">
<!-- 间距和尺寸 -->
<div class="p-4 m-2 w-full max-w-md">
<!-- 文字样式 -->
<h1 class="text-2xl font-bold text-gray-800 mb-4">
标题
</h1>
<!-- 响应式设计 -->
<div class="md:flex md:space-x-4">
<!-- 卡片示例 -->
<div class="bg-white rounded-lg shadow-md p-6 mb-4 md:mb-0">
<!-- 悬停和状态效果 -->
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
点击我
</button>
</div>
</div>
</div>
</div>
</template>
5.常用类说明
布局类:
- flex: 弹性布局
- grid: 网格布局
- container: 容器
- hidden/block/inline: 显示方式
间距:
- p-{size}: padding
- m-{size}: margin
- space-x/y-{size}: 子元素间距
尺寸:
- w-{size}: 宽度
- h-{size}: 高度
- max-w-{size}: 最大宽度
颜色:
- text-{color}: 文字颜色
- bg-{color}: 背景色
- border-{color}: 边框颜色
响应式:
- sm: >= 640px
- md: >= 768px
- lg: >= 1024px
- xl: >= 1280px
6.实用技巧
<template>
<!-- 组合使用 -->
<div class="transition-all hover:scale-105 active:scale-95">
<!-- 暗黑模式 -->
<div class="dark:bg-gray-800 dark:text-white">
内容
</div>
<!-- 自定义组合类 -->
<button class="btn-primary">
使用自定义类
</button>
</div>
</template>