TailwindCSS使用记录
简介
Tailwind CSS 是一个实用优先(Utility-first)的 CSS 框架,通过在 HTML 中组合原子类来构建界面,而不是编写大量自定义 CSS。适合快速原型开发和组件化项目。
安装与配置
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
tailwind.config.js 中通过 content 指定扫描路径,避免生产包体积过大:
module.exports = {
content: ['./src/**/*.{html,js,jsx,ts,tsx,vue}'],
theme: {
extend: {},
},
plugins: [],
}
入口 CSS 引入三层指令:
@tailwind base;
@tailwind components;
@tailwind utilities;
常用工具类
布局
<div class="flex items-center justify-between gap-4">
<div class="grid grid-cols-3 gap-2">...</div>
</div>
间距与尺寸
p-4/px-6/py-2:内边距m-4/mt-8:外边距w-full/h-screen/max-w-2xl:宽高
文字与颜色
<h1 class="text-2xl font-bold text-gray-900">标题</h1>
<p class="text-sm text-gray-500 leading-relaxed">正文</p>
响应式
前缀表示断点:sm:md:lg:xl:
<div class="w-full md:w-1/2 lg:w-1/3">...</div>
状态变体
<button class="bg-blue-500 hover:bg-blue-600 focus:ring-2 active:scale-95">
提交
</button>
自定义文件中使用 theme
如果自定义的 CSS 文件中想要引用已定义的 design token,可以通过 theme() 函数引用:
article {
color: theme('colors.violet.500');
}
article code {
color: theme('colors.sky.500');
}
@apply 提取组件样式
重复的组合类可以提取为组件层:
@layer components {
.btn-primary {
@apply px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600;
}
}
与框架集成
- Vite / Webpack:PostCSS 插件链中启用
tailwindcss - React / Vue:直接在 JSX / 模板中写类名,配合
clsx或classnames做条件组合 - 生产构建:Tailwind 3+ 默认按需生成,只打包实际用到的类
使用心得
- 先熟悉 spacing / color / typography 命名规律,写起来会很快
- 复杂组件用
@apply或拆成小组件,避免单行类名过长 tailwind.config.js的extend适合放品牌色和自定义间距,不要覆盖默认值除非必要