Tailwind CSS¶
简介¶
Tailwind CSS 是一个 utility-first 的 CSS 框架,通过原子化的工具类直接在 HTML 中编写样式,无需手写 CSS 文件。
基本用法¶
<!-- 传统方式 -->
<button class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition">
点击
</button>
<!-- Flex 布局 -->
<div class="flex items-center justify-between gap-4">
<span class="text-lg font-bold">标题</span>
<span class="text-gray-500 text-sm">副标题</span>
</div>
响应式设计¶
断点前缀:
sm:≥ 640pxmd:≥ 768pxlg:≥ 1024pxxl:≥ 1280px2xl:≥ 1536px
常用工具类¶
排版¶
text-sm/text-base/text-lg/text-xl字号。font-bold/font-semibold/font-medium字重。text-gray-500/text-blue-600颜色。text-center/text-left对齐。leading-relaxed行高。tracking-wide字间距。
间距¶
p-4padding 1rem,px-4水平,py-4垂直。m-4margin,mx-auto水平居中。gap-4flex/grid 子元素间距。
颜色¶
bg-white/bg-gray-100/bg-blue-600背景色。border-gray-200边框色。ring-2 ring-blue-500聚焦环。opacity-50透明度。
尺寸¶
w-full/w-1/2/w-screen宽度。h-screen/h-auto高度。max-w-sm/max-w-4xl最大宽度。min-h-screen最小高度。
布局¶
flex/grid/block/hidden/inline-flex。items-center/justify-between。grid-cols-3/col-span-2。absolute/relative/fixed/sticky。z-10/z-50。
状态修饰符¶
<button class="bg-blue-600 hover:bg-blue-700 focus:ring-2 active:bg-blue-800 disabled:opacity-50">
按钮
</button>
<!-- 暗色模式 -->
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
内容
</div>
自定义配置 (tailwind.config.js)¶
/** @type {import('tailwindcss').Config} */
export default {
content: ["./src/**/*.{html,tsx}"],
darkMode: "class",
theme: {
extend: {
colors: {
primary: "#2563eb",
},
fontFamily: {
sans: ["Inter", "sans-serif"],
},
},
},
plugins: [],
};
@apply 复用¶
在 CSS 文件中复用工具类:
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
.btn-primary {
@apply bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition;
}
}
与 CSS-in-JS 对比¶
- Tailwind:零运行时,样式在构建时生成,性能好。
- CSS-in-JS(styled-components、emotion):运行时注入,灵活但有性能开销。
- 推荐:新项目用 Tailwind,已有 CSS-in-JS 项目按需迁移。