Skip to content

Tailwind CSS 速查表

用于快速 UI 开发的实用优先 CSS 框架。

01

入门

通过 CDN 安装

CDN 脚本是使用 Tailwind 原型设计的最快方式。它通过扫描你的标记在运行时生成实用类。生产环境建议使用 PostCSS 或 CLI 构建,以清除未使用的类并打包出极小的 CSS 体积。

tailwind
<!-- Quick start: drop this in <head> -->
<script src="https://cdn.tailwindcss.com"></script>

<!-- Tailwind scans class names in your HTML and generates styles on the fly -->
<h1 class="text-3xl font-bold text-blue-600">Hello Tailwind</h1>

项目搭建(CLI)

content 数组至关重要——Tailwind 只生成它在这些文件中找到的类(摇树优化)。漏掉某个路径是『我的类不见了』问题的头号原因。开发时使用 --watch。

tailwind
# Install Tailwind as a project dependency
npm install -D tailwindcss
npx tailwindcss init

# tailwind.config.js — tell Tailwind where your templates live
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{html,js,jsx,ts,tsx}"],
  theme: { extend: {} },
  plugins: [],
};

# Build CSS
npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch

Input CSS 指令

@tailwind 指令按顺序注入 Tailwind 的三层:base(重置)、components、utilities。@layer 让你将自己的 CSS 加入到正确的层叠层中。@apply 将实用样式内联到自定义规则中。

tailwind
/* src/input.css — the three layers Tailwind uses */
@tailwind base;      /* normalize/reset + base element styles */
@tailwind components; /* component classes you register */
@tailwind utilities;  /* the utility classes themselves */

/* Add custom CSS after the directives */
@layer base {
  h1 { @apply text-2xl; }
}

实用优先的心智模型

Tailwind 的理念:通过组合小而单一用途的实用类来构建 UI,而不是发明语义化的类名。这使 CSS 保持扁平、避免死代码,并通过共享的间距/颜色标尺让设计保持一致。

tailwind
<!-- Instead of naming custom classes, compose utilities -->
<button class="bg-blue-600 hover:bg-blue-700 text-white
               font-medium py-2 px-4 rounded-lg shadow
               transition-colors duration-200">
  Save
</button>

<!-- Equivalent to writing CSS: .btn { background, padding, radius... } -->
<!-- But each utility maps to a single, predictable declaration. -->

配置与主题扩展

使用 theme.extend 在不替换默认值的情况下添加。在 theme 顶层(而非 extend)定义某键会完整替换该标尺。自定义颜色如 brand-500 会生成 bg-brand-500、text-brand-500、border-brand-500 等。

tailwind
// tailwind.config.js
module.exports = {
  content: ["./src/**/*.{html,tsx}"],
  theme: {
    extend: {
      colors: {
        brand: { 500: "#06B6D4", 600: "#0891B2" },
      },
      fontFamily: {
        sans: ["Inter", "system-ui", "sans-serif"],
      },
      spacing: { 128: "32rem" },
    },
  },
  plugins: [],
};
02

颜色

文本、背景与边框颜色

颜色实用类遵循 {属性}-{颜色}-{色阶} 模式。色阶从 50(最浅)到 950(最深)。常见属性:text-、bg-、border-、ring-、fill-、stroke-、from-/to-/via-(渐变)。

tailwind
<p class="text-red-500">Red text</p>
<div class="bg-blue-100">Light blue background</div>
<span class="border border-gray-300">Gray border</span>
<button class="bg-emerald-500 hover:bg-emerald-600">Emerald</button>

透明度修饰符

在任何颜色实用类后追加 /{透明度} 即可设置其 alpha 通道。底层使用 color-mix 或 rgba,适用于 text、bg、border、ring 等。这是无需定义新调色板条目即可调色的最简洁方式。

tailwind
<div class="bg-black/50">50% black overlay</div>
<p class="text-blue-600/75">75% opacity blue text</p>
<div class="border-gray-900/10">10% gray border</div>
<button class="bg-indigo-500 hover:bg-indigo-500/90">Slight fade</button>

渐变

用 bg-gradient-to-{方向} 配合 from-、via-、to- 颜色停止点。方向包括 t(上)、b、l、r、tr、tl、br、bl。径向/锥形渐变(v3.3+)使用 bg-gradient-radial(需插件或任意值)。

tailwind
<div class="bg-gradient-to-r from-purple-500 to-pink-500">
  Left to right gradient
</div>

<div class="bg-gradient-to-tr from-yellow-400 via-red-500 to-pink-600">
  Three-stop diagonal gradient
</div>

<div class="bg-gradient-to-b from-sky-400 to-sky-900">Vertical</div>

自定义与任意颜色

方括号中的任意值让你无需修改配置即可使用任何 CSS 颜色——非常适合一次性场景。对于重复使用的颜色,在 theme.extend.colors 中定义,以便支持透明度修饰符并获得一致的命名。

tailwind
<!-- Arbitrary hex/rgb value -->
<div class="bg-[#1da1f2]">Twitter blue</div>
<p class="text-[rgb(255,0,0)]">Red</p>

<!-- Custom color from your theme -->
<button class="bg-brand-600">My brand color</button>

<!-- Current color / transparent -->
<div class="bg-transparent border border-current">Transparent</div>

调色板概览

Tailwind 的调色板用四个中性色家族替换了通用的 'gray':slate(冷蓝)、gray、zinc、neutral 和 stone(暖色)。为整个项目选一个以保证中性色一致。每种颜色有 11 个色阶(50、100、...、950)。

tailwind
<!-- Tailwind ships 22 color families, each 50-950 -->
<!-- slate gray zinc neutral stone red orange amber yellow -->
<!-- lime green emerald teal cyan sky blue indigo violet -->
<!-- purple fuchsia pink rose -->

<p class="text-slate-900">Primary text</p>
<p class="text-slate-500">Secondary text</p>
<p class="text-slate-400">Muted text</p>

<!-- Use slate/zinc/neutral/stone instead of plain gray -->
<!-- They have subtler blue/warm tones than old gray-*. -->
03

排版

字号与字重

text-{size} 映射到基于 rem 的标尺(text-base = 1rem)。font-{weight} 覆盖 100-900。text-[42px] 等任意值也可用。除非用 leading-* 覆盖,否则行高会随字号自动缩放。

tailwind
<p class="text-xs">12px</p>
<p class="text-sm">14px</p>
<p class="text-base">16px (default)</p>
<p class="text-lg">18px</p>
<p class="text-2xl">24px</p>
<p class="text-7xl">72px</p>

<p class="font-thin">100</p>
<p class="font-normal">400</p>
<p class="font-medium">500</p>
<p class="font-semibold">600</p>
<p class="font-bold">700</p>
<p class="font-black">900</p>

行高与字间距

leading-* 设置行高(数字 = rem,命名 = 相对值)。tracking-* 设置字间距。uppercase + tracking-wider + text-xs 的组合是小型大写风格标签和眉题的常见 Tailwind 写法。

tailwind
<p class="leading-none">Line height 1</p>
<p class="leading-tight">1.25</p>
<p class="leading-normal">1.5 (default)</p>
<p class="leading-loose">2</p>
<p class="leading-6">1.5rem fixed</p>

<p class="tracking-tight">-0.025em</p>
<p class="tracking-normal">0</p>
<p class="tracking-wide">0.025em</p>
<p class="tracking-widest">0.1em</p>

<!-- Uppercase + tracking for labels -->
<span class="uppercase tracking-wider text-xs font-bold">Label</span>

文本对齐与装饰

text-{left,center,right,justify} 对齐行内内容。underline/line-through/no-underline 切换文本装饰;decoration-{1-4} 设置粗细,underline-offset-{n} 定位。hover:underline 是导航链接的标准模式。

tailwind
<p class="text-left">Left</p>
<p class="text-center">Center</p>
<p class="text-right">Right</p>
<p class="text-justify">Justified long paragraph...</p>

<a class="underline">Underlined</a>
<a class="line-through">Strikethrough</a>
<a class="no-underline hover:underline">Hover underline</a>

<a class="decoration-2 underline-offset-4">Thicker underline, offset</a>

字体族与任意字体

默认提供三种字体栈:sans(系统 UI)、serif、mono。可在 theme.extend.fontFamily 添加更多(如 display、body)。一次性字体用 font-['Name']。记得在 CSS/HTML 中 @import 或 <link> 实际的 web 字体。

tailwind
<p class="font-sans">Default sans-serif stack</p>
<p class="font-serif">Serif stack</p>
<p class="font-mono">Monospace</p>

<!-- Arbitrary font family -->
<p class="font-['Georgia']">Georgia</p>

<!-- After configuring theme.extend.fontFamily -->
<p class="font-display">Custom display font</p>

文本溢出与截断

truncate = overflow-hidden text-ellipsis whitespace-nowrap(单行 + 省略号)。line-clamp-{1-6} 截断为 N 行(使用 -webkit-line-clamp)。自由换行用 break-words 或 break-all 控制长单词断行。

tailwind
<!-- Single-line ellipsis -->
<p class="truncate w-64">
  Very long text that will be cut off with an ellipsis at the end...
</p>

<!-- Clip without ellipsis -->
<p class="overflow-clip w-32">Long text clipped</p>

<!-- Multi-line clamp (2 lines) -->
<p class="line-clamp-2">
  Multi-line paragraph that gets clamped after two lines
  with an ellipsis, useful for card previews and previews.
</p>
04

间距

内边距与外边距

间距实用类使用单一的 4px 基准标尺:1 = 0.25rem = 4px。p* / m* 用于所有边,px/py 用于成对轴向,pt/pr/pb/pl 或 mt/mr/mb/ml 用于单边。mx-auto 让块级元素水平居中。

tailwind
<!-- p-* = padding, m-* = margin -->
<div class="p-4">16px all sides</div>
<div class="px-4 py-2">16px horizontal, 8px vertical</div>
<div class="pt-2 pr-4 pb-2 pl-4">Per side (top/right/bottom/left)</div>

<div class="m-8">32px margin all sides</div>
<div class="mx-auto">Center a block (auto L/R margin)</div>
<div class="mt-0 mb-4">No top margin, 16px bottom</div>

间距标尺

同一套标尺管理 padding、margin、gap、width、height 等——这种一致性是 Tailwind 的超能力。负值(-mt-2)用于重叠和偏移拉动。任意值 p-[13px] 在需要时跳出标尺,但应少用。

tailwind
<!-- The default scale (in px) -->
0 = 0px      1 = 4px     2 = 8px     3 = 12px    4 = 16px
5 = 20px     6 = 24px    8 = 32px    10 = 40px   12 = 48px
16 = 64px    20 = 80px   24 = 96px   32 = 128px  48 = 192px

<!-- Negative margins -->
<div class="-mt-4">Pulls up by 16px</div>
<div class="-ml-2">Pulls left by 8px</div>

<!-- Arbitrary values -->
<div class="p-[13px] mt-[7px]">Custom sizes</div>

子元素之间的间距

space-x-* / space-y-* 在兄弟元素之间添加外边距(而非四周)——非常适合垂直堆叠和徽章行。注意:space-x 使用 margin-left,因此与 flex justify 配合不佳;flex 中优先使用 gap-* 实用类(见 Flexbox)。

tailwind
<div class="space-y-4">
  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 3</div>
</div>
<!-- Adds 16px margin-top to every child except the first -->

<div class="space-x-2 flex">
  <span>A</span><span>B</span><span>C</span>
</div>
<!-- Adds 8px margin-left to every child except the first -->

宽度与高度

w-* / h-* 使用间距标尺,外加分数(1/2、1/3、2/3、1/4...)、screen/full,以及命名尺寸(xs..7xl 用于 max-width)。max-w-{size} 限制宽度——将页面内容包在 max-w-md mx-auto 中可获得可读行宽。w-fit / w-max 使用内在尺寸。

tailwind
<div class="w-16 h-16">64x64 box</div>
<div class="w-1/2 h-full">50% width, full height</div>
<div class="w-screen h-screen">Full viewport</div>
<div class="w-96">24rem fixed</div>
<div class="max-w-md mx-auto">Capped width, centered</div>
<div class="min-h-screen">At least full viewport tall</div>

<!-- Modern: fit-content, intrinsic sizing -->
<div class="w-fit">Shrinks to content</div>

Flex 与 Grid 的 gap

gap-* 是为 flex/grid 子元素设置间距的现代方式——取代了旧的 space-x/space-y 外边距方案。设置 gap 用于两个轴向,或 gap-x/gap-y 单独设置。使用与 padding/margin 相同的间距标尺。

tailwind
<div class="flex gap-4">
  <div>A</div><div>B</div><div>C</div>
</div>
<!-- 16px between flex children, no margin hacks needed -->

<div class="grid grid-cols-3 gap-2 gap-y-4">
  <div>1</div><div>2</div><div>3</div>
  <div>4</div><div>5</div><div>6</div>
</div>
<!-- gap = both axes; gap-x / gap-y for per-axis -->
05

Flexbox

基础 Flex 容器

flex 设置 display:flex;inline-flex 设置 display:inline-flex。flex-col 将主轴切换为垂直——配合 gap 是构建垂直堆叠的最简洁方式。默认方向为 row(水平)。

tailwind
<div class="flex">
  <div>A</div><div>B</div><div>C</div>
</div>

<div class="inline-flex gap-2">
  <span>Badge</span><span>Badge</span>
</div>

<!-- Vertical stack = flex-col (often cleaner than space-y) -->
<div class="flex flex-col gap-4">
  <div>Row 1</div>
  <div>Row 2</div>
</div>

主轴对齐与交叉对齐

justify-* 控制主轴(flex-row 中为水平);items-* 控制交叉轴(flex-row 中为垂直)。组合 'flex justify-center items-center' 让内容双向居中——这是 Tailwind 中最常用的居中代码片段。

tailwind
<div class="flex justify-start">   <!-- left   --></div>
<div class="flex justify-center">  <!-- center --></div>
<div class="flex justify-between"> <!-- spread --></div>
<div class="flex justify-around">  <!-- equal space around --></div>
<div class="flex justify-end">     <!-- right  --></div>

<!-- Cross axis (perpendicular to main) -->
<div class="flex items-center">     <!-- vertically center --></div>
<div class="flex items-start">      <!-- top align --></div>
<div class="flex items-end">        <!-- bottom align --></div>
<div class="flex items-stretch">    <!-- fill height --></div>

Flex 增长、收缩与基准

flex-1 = flex:1 1 0%(增长填满,可收缩,基准 0)。flex-none = 不增长也不收缩(固定)。flex-grow-0 / flex-shrink-0 单独禁用增长/收缩。basis-{n} 设置增长前的初始尺寸。

tailwind
<div class="flex">
  <div class="flex-1">Grows to fill</div>
  <div class="flex-none">Never shrinks (fixed)</div>
  <div class="flex-initial">Default size, can shrink</div>
</div>

<div class="flex">
  <div class="flex-grow-0 w-20">Fixed 80px</div>
  <div class="flex-grow basis-0">Takes remaining</div>
</div>

<!-- Responsive: sidebar collapses on mobile -->
<div class="flex flex-col md:flex-row">
  <aside class="md:w-64 md:flex-shrink-0">Sidebar</aside>
  <main class="flex-1">Main</main>
</div>

Flex 换行与排序

flex-wrap 让子元素流到新行(默认 nowrap 会溢出)。order-{n} 在不改变 DOM 的情况下对子元素重新排序视觉位置——order-first/last 是快捷方式。适用于在不同断点需要不同视觉顺序的响应式布局。

tailwind
<div class="flex flex-wrap gap-4">
  <div class="w-40">Card</div>
  <div class="w-40">Card</div>
  <div class="w-40">Card</div>
  <!-- Cards wrap to next line instead of overflowing -->
</div>

<div class="flex flex-wrap-reverse">Wrap backwards</div>
<div class="flex flex-nowrap">No wrapping (default)</div>

<!-- Reorder children -->
<div class="flex">
  <div class="order-last">First in DOM, last visually</div>
  <div class="order-first">Last in DOM, first visually</div>
  <div class="order-2">Custom order</div>
</div>

居中模式

flex items-center justify-center 是经典的居中代码片段——适用于任何内容尺寸。粘性页脚模式(min-h-screen + flex-col + flex-1 main)即使在内容很少时也能将页脚推到底部。

tailwind
<!-- Center anything both axes (classic) -->
<div class="flex items-center justify-center h-screen">
  <div>Dead center</div>
</div>

<!-- Sticky footer pattern -->
<div class="flex flex-col min-h-screen">
  <header>Header</header>
  <main class="flex-1">Content grows</main>
  <footer>Footer</footer>
</div>

<!-- Space between with centered item -->
<div class="flex items-center justify-between">
  <button>Left</button>
  <h1 class="absolute left-1/2 -translate-x-1/2">Centered title</h1>
  <button>Right</button>
</div>
06

Grid

基础 Grid

grid 设置 display:grid。grid-cols-{n} 定义固定的列数(1-12)。auto-rows-fr 让每一行等高(各 1fr)。gap-* 与 flex 中的作用相同,用于间距轨道。

tailwind
<div class="grid grid-cols-3 gap-4">
  <div>1</div><div>2</div><div>3</div>
  <div>4</div><div>5</div><div>6</div>
</div>

<!-- Auto rows set the row height -->
<div class="grid grid-cols-2 auto-rows-fr gap-2">
  <div>Equal-height rows</div>
  <div>Equal-height rows</div>
</div>

<!-- Inline grid -->
<span class="inline-grid grid-cols-2 gap-1">...</span>

响应式列

auto-fit + minmax 模式是一个强大的响应式技巧:列至少 200px 并拉伸填满行,自动换行——无需媒体查询。如需更多控制,可结合显式的响应式 grid-cols-*。

tailwind
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
  <!-- 1 column on mobile, 2 on small, 3 on large, 4 on xl -->
</div>

<!-- Auto-fit / minmax for card grids that wrap naturally -->
<div class="grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-4">
  <div>Card</div><div>Card</div><div>Card</div>
</div>

列与行的跨度

col-span-{n} / row-span-{n} 让元素覆盖多个轨道。col-start-{n} / col-end-{n} 将元素放置到显式的网格线。组合使用可在无媒体查询的情况下构建复杂的杂志风格布局。

tailwind
<div class="grid grid-cols-3 grid-rows-3 gap-2">
  <div class="col-span-2">Spans 2 cols</div>
  <div>1 col</div>
  <div class="row-span-2">Spans 2 rows</div>
  <div class="col-span-2 row-span-2">Big tile</div>
  <div>1 col</div>
  <div>1 col</div>
</div>

<!-- Explicit placement -->
<div class="col-start-2 col-end-4 row-start-1">
  Placed at column 2-4, row 1
</div>

通过任意值定义网格模板区域

方括号中的任意值让你指定任何 grid-template 语法:grid-cols-[200px_1fr_100px] 创建三个自定义宽度的轨道(下划线会变成空格)。命名 grid-template-areas 不是内置实用类——在自定义类中定义或通过 col/row span 实现布局。

tailwind
<div class="grid grid-cols-[200px_1fr] grid-rows-[auto_1fr_auto] gap-4
            min-h-screen">
  <aside class="row-span-3">Sidebar</aside>
  <header>Header</header>
  <main>Main</main>
  <footer>Footer</footer>
</div>

<!-- Named template areas need custom CSS or plugin: -->
<style>
  .app { grid-template-areas: "h h" "s m" "f f"; }
</style>

间距与对齐

justify-items-* / content-* 控制项目在单元格中的位置以及轨道在容器中的位置。place-items-center 是 justify-items + items-content(双轴)的简写。place-content-center 让整个网格块居中。

tailwind
<div class="grid grid-cols-3 gap-4 gap-x-8 gap-y-2">
  <!-- 32px col gap, 8px row gap -->
</div>

<!-- Align whole grid tracks -->
<div class="grid grid-cols-2 justify-items-center">
  <div>Each item centered in its cell</div>
</div>

<div class="grid grid-cols-2 content-center h-64">
  <div>Vertically centers the rows</div>
</div>

<div class="grid grid-cols-2 place-items-center">
  <!-- Both axes at once -->
</div>
07

边框

边框宽度与颜色

border 在所有边设置 1px;border-{2,4,8} 设置粗细。border-{t,r,b,l,x,y} 针对特定边。border-dashed/dotted/double 设置样式。务必配合 border-{color}——Tailwind 的默认边框颜色是 gray-200(v3 中从 gray-300 改动)。

tailwind
<div class="border">1px all sides</div>
<div class="border-2">2px</div>
<div class="border-4 border-red-500">4px red</div>

<div class="border-t border-b">Only top & bottom</div>
<div class="border-l-4 border-emerald-500">Left accent bar</div>
<div class="border-x border-gray-300">Left & right</div>

<div class="border border-dashed border-gray-400">Dashed</div>
<div class="border border-dotted">Dotted</div>
<div class="border border-double">Double</div>

圆角

rounded-{none,sm,md,lg,xl,2xl,3xl,full} 缩放圆角;rounded-full 制造胶囊或完美圆形(当宽=高时)。按角:rounded-{tl,tr,bl,br}-{size},按边:rounded-{t,b,l,r}-{size}。头像圆使用 rounded-full + 相等的 w/h。

tailwind
<div class="rounded">0.25rem</div>
<div class="rounded-md">0.375rem</div>
<div class="rounded-lg">0.5rem</div>
<div class="rounded-xl">0.75rem</div>
<div class="rounded-2xl">1rem</div>
<div class="rounded-full">Fully rounded (pill/circle)</div>

<div class="rounded-t-lg rounded-b-none">Top only</div>
<div class="rounded-l-full">Left side pill</div>
<div class="rounded-tr-2xl rounded-bl-2xl">Per-corner</div>

子元素之间的分割线

divide-{x,y} 在兄弟元素之间添加边框——比给每个子元素加 border-t 干净得多。divide-{color} 和 divide-{width} 自定义它们。在子元素上配合 py/px 以在列表和表格中获得舒适的间距。

tailwind
<ul class="divide-y divide-gray-200">
  <li class="py-2">Item 1</li>
  <li class="py-2">Item 2</li>
  <li class="py-2">Item 3</li>
</ul>
<!-- Adds a 1px top border to each child except the first -->

<div class="flex divide-x divide-gray-300">
  <div class="px-4">Col 1</div>
  <div class="px-4">Col 2</div>
  <div class="px-4">Col 3</div>
</div>

Ring(类 outline)

Ring 是基于 box-shadow 的轮廓,不影响布局(与 border 不同)且能很好地叠加。ring-{n} 设置宽度,ring-{color} 设置颜色,ring-offset-{n} 在元素和 ring 之间添加空白。focus:ring 模式是标准的可访问焦点样式。

tailwind
<button class="ring-2 ring-blue-500 ring-offset-2">
  Ring with offset
</button>

<input class="ring-2 ring-red-500 focus:ring-2 focus:ring-blue-500" />

<button class="ring-1 ring-inset ring-gray-300">Inset ring</button>

<!-- Focus ring pattern (accessibility) -->
<button class="focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
  Accessible focus
</button>

Outline

outline-* 使用真正的 CSS outline 属性(在 border box 之外,无布局影响)。Tailwind 中更推荐 ring,因为它是分层 box-shadow——多个 ring 可叠加且 ring-offset 提供干净间隙。当你明确需要 CSS outline 行为时使用 outline。

tailwind
<input class="outline-none" />  <!-- Remove default -->
<input class="outline outline-2 outline-blue-500" />
<input class="outline-dashed outline-1 outline-gray-400" />

<input class="focus:outline-none focus:ring-2 focus:ring-blue-500"
       type="text" />

<!-- Outline vs ring: outline is drawn outside border-box,
     ring is a box-shadow (can stack, has offset) -->
08

背景

背景色与附件

bg-{color} 设置 background-color,用 /{透明度} 设置 alpha。bg-fixed 创造视差效果(背景在内容滚动时保持不动)。bg-clip-{padding,border,content} 控制背景在边框/内容下延伸的范围。

tailwind
<div class="bg-blue-500">Solid color</div>
<div class="bg-blue-500/50">50% opacity</div>
<div class="bg-fixed">Parallax (fixed on scroll)</div>
<div class="bg-local">Scrolls with content</div>
<div class="bg-scroll">Default</div>

<!-- Clip: padding-box, border-box, content-box -->
<div class="bg-clip-padding border-4 border-dashed">Padding clip</div>
<div class="bg-clip-border">Border clip</div>

背景图与渐变

使用 bg-[url('/path/to/img.jpg')] 通过任意 URL 设置 background-image(给 URL 加引号)。bg-cover 填充元素并保持宽高比;bg-contain 让整张图片适配。bg-{center,top,bottom,left,right} 和 bg-{repeat,no-repeat,repeat-x,repeat-y} 控制定位和重复。

tailwind
<div class="bg-gradient-to-r from-cyan-500 to-blue-500">
  Horizontal gradient
</div>

<!-- Image with arbitrary value -->
<div class="bg-[url('/hero.jpg')] bg-cover bg-center h-64">
  Hero with cover image
</div>

<!-- Repeat & position -->
<div class="bg-repeat-x bg-[url('/pattern.png')]">Repeat horizontally</div>
<div class="bg-no-repeat bg-top">No repeat, top aligned</div>

渐变方向与停止点

from-/via-/to- 设置渐变颜色停止点;bg-gradient-to-{direction} 设置角度。to-br 等对角方向常用于暖色 hero 渐变。原生径向/锥形渐变需插件或任意值:bg-[radial-gradient(...)]。

tailwind
<!-- Directions: to-t, to-b, to-l, to-r, to-tr, to-tl, to-br, to-bl -->
<div class="bg-gradient-to-br from-amber-400 to-orange-600">
  Bottom-right diagonal
</div>

<!-- Three-stop gradient -->
<div class="bg-gradient-to-r from-green-400 via-teal-500 to-blue-600">
  Multi-stop
</div>

<!-- Radial (Tailwind v3.3+) -->
<div class="bg-gradient-radial from-pink-400 to-purple-700">
  Radial (may need plugin)
</div>

背景尺寸与定位

bg-cover vs bg-contain 是 hero 图与 logo 各自的关键选择。cover 填充盒子(裁剪溢出);contain 适配整张图片(可能留空白)。bg-cover + bg-center 组合是标准的响应式 hero 图方案。

tailwind
<div class="bg-cover bg-center h-48 bg-[url('/img.jpg')]">
  Cover: fills container, may crop
</div>

<div class="bg-contain bg-center h-48 bg-no-repeat bg-[url('/logo.png')]">
  Contain: fits entire image, may letterbox
</div>

<div class="bg-top-left bg-[url('/img.jpg')] bg-cover">Top-left anchor</div>
<div class="bg-[center_top]">Custom position</div>

背景混合模式

bg-blend-{mode} 控制多个背景层(图片 + 颜色)如何合成。multiply、screen、overlay、darken、lighten 较常见。为提高文字可读性而加深图片时,更干净的方式是在上方覆盖半透明渐变(右例)。

tailwind
<div class="bg-blend-multiply bg-[url('/photo.jpg')] bg-blue-500">
  Multiplies image with blue overlay
</div>

<!-- Common overlay pattern: dark gradient over image -->
<div class="relative">
  <img src="/hero.jpg" class="w-full" />
  <div class="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent">
    Overlay
  </div>
</div>
09

阴影

盒阴影标尺

阴影标尺(sm、default、md、lg、xl、2xl)在你的应用中提供一致的悬浮感。shadow-inner 创建内阴影,适用于凹陷和按压状态。卡片通常用 shadow-md 配合 hover:shadow-lg 实现上浮效果。

tailwind
<div class="shadow-sm">Subtle</div>
<div class="shadow">Default</div>
<div class="shadow-md">Medium</div>
<div class="shadow-lg">Large</div>
<div class="shadow-xl">Extra large</div>
<div class="shadow-2xl">Huge</div>
<div class="shadow-none">No shadow</div>

<!-- Inner shadow -->
<div class="shadow-inner">Pressed-in look</div>

彩色阴影

shadow-{color} 用颜色为盒阴影着色(使用相同的调色板)。配合 /{透明度} 可创建发光效果。彩色阴影是让按钮和强调元素更具活力和品牌感的快捷方式。

tailwind
<div class="shadow-lg shadow-blue-500/50">
  Blue tinted shadow
</div>

<div class="shadow-xl shadow-cyan-500/30">
  Cyan glow effect
</div>

<div class="shadow-md shadow-black/30">Darker default</div>

<button class="bg-emerald-500 shadow-lg shadow-emerald-500/50">
  Colored button shadow
</button>

悬停上浮模式

hover:shadow-{更大} 配合 transition-shadow 是标准的卡片悬停模式。再搭配 hover:-translate-y-0.5 和 active:translate-y-0 可为按钮提供物理按压反馈——小而令人愉悦的交互细节。

tailwind
<div class="bg-white rounded-xl shadow-md hover:shadow-xl
            transition-shadow duration-300 p-6 cursor-pointer">
  Card with hover lift
</div>

<!-- Combined with slight translate for tactile feel -->
<button class="shadow-md hover:shadow-sm active:shadow-sm
               hover:-translate-y-0.5 active:translate-y-0
               transition-all">
  Tactile button
</button>

Drop Shadow(用于 SVG/文本)

drop-shadow 使用 CSS filter:drop-shadow(),它会跟随元素的实际形状(非常适合带透明度的 SVG 和 PNG),而 box-shadow 只对盒子打阴影。drop-shadow-md 用于文本是 text-shadow 的柔和替代方案。

tailwind
<h1 class="drop-shadow-md">Text with shadow</h1>

<svg class="drop-shadow-lg">
  <!-- SVG shape gets shadowed as a whole -->
</svg>

<!-- Combine with rotate for dramatic effects -->
<div class="rotate-3 drop-shadow-2xl">Tilted card</div>

<!-- Filter utilities affect the element as a whole image -->
<div class="blur-sm brightness-110">Image filters</div>

任意与分层阴影

对于默认标尺之外的阴影,使用任意值语法 shadow-[...]。对于复杂的分层阴影(那种看起来真正高级的阴影),在自定义 CSS 类中定义一次更干净——Tailwind 的单层阴影无法匹配多层深度。

tailwind
<div class="shadow-[0_8px_30px_rgb(0,0,0,0.12)]">
  Custom shadow via arbitrary value
</div>

<!-- Multiple layered shadows via custom CSS -->
<style>
  .card-shadow {
    box-shadow:
      0 1px 2px rgba(0,0,0,0.04),
      0 4px 8px rgba(0,0,0,0.06),
      0 12px 24px rgba(0,0,0,0.08);
  }
</style>
<div class="card-shadow">Layered elevation</div>
10

响应式设计

断点

Tailwind 是移动优先:基础样式处处适用,断点前缀在 min-width 时生效。顺序很重要——按从小到大编写类(text-sm md:text-base lg:text-lg)。断点匹配常见设备宽度,且可配置。

tailwind
<!-- Default = mobile first, then min-width overrides -->
<!-- sm: 640px, md: 768px, lg: 1024px, xl: 1280px, 2xl: 1536px -->

<div class="text-sm md:text-base lg:text-lg">
  Grows with viewport
</div>

<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4">
  Responsive grid
</div>

<!-- Hide on small screens, show on large -->
<div class="hidden md:block">Desktop only</div>
<div class="block md:hidden">Mobile only</div>

响应式 Flex/Grid

flex-col md:flex-row 模式是响应式布局的支柱:手机上垂直堆叠,桌面端并排。配合响应式 grid-cols-* 用于卡片网格。始终先设计移动布局,再向上增强。

tailwind
<!-- Stack on mobile, row on desktop -->
<div class="flex flex-col md:flex-row gap-4">
  <aside class="md:w-64">Sidebar</aside>
  <main class="flex-1">Main</main>
</div>

<!-- 1 col mobile -> 2 col tablet -> 4 col desktop -->
<div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
  <div>Card</div>
</div>

<!-- Sidebar that hides on mobile -->
<aside class="hidden lg:block lg:w-1/4">Sidebar</aside>

容器与最大宽度

container 在每个断点居中内容并限制宽度(需手动添加居中和内边距)。手动模式 'max-w-7xl mx-auto px-4 sm:px-6 lg:px-8' 是最常见的页面包装器。文章应限制在 max-w-2xl/3xl 以获得可读行宽。

tailwind
<div class="container mx-auto px-4">
  <!-- Centers content and caps width at each breakpoint -->
</div>

<!-- Or manually cap width -->
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
  Standard page wrapper
</div>

<article class="prose max-w-none lg:max-w-2xl mx-auto">
  Article with readable line length
</article>

按断点显示/隐藏

hidden md:block / block md:hidden 是在移动端和桌面端之间切换元素的经典模式(如汉堡菜单 vs 完整导航)。print:block 仅在打印时显示。min-[1200px]: 等任意断点可针对自定义宽度。

tailwind
<!-- Mobile-only nav -->
<nav class="block md:hidden">Mobile menu</nav>

<!-- Desktop-only nav -->
<nav class="hidden md:flex">Desktop menu</nav>

<!-- Hide print-only content -->
<div class="hidden print:block">Only shows when printing</div>

<!-- Custom breakpoint -->
<div class="min-[1200px]:flex">Custom MQ</div>

响应式排版与间距

在每个断点放大字号和间距以建立视觉层级。要实现真正的流式字号,通过任意值使用 clamp():text-[clamp(2rem,5vw,4rem)]——标题随视口在最小和最大值之间平滑增长。

tailwind
<h1 class="text-3xl sm:text-4xl md:text-5xl lg:text-6xl
         font-bold leading-tight">
  Fluid-ish heading
</h1>

<section class="px-4 sm:px-6 lg:px-12 py-8 md:py-12 lg:py-20">
  Scales padding with viewport
</section>

<!-- True fluid type with clamp via arbitrary value -->
<h1 class="text-[clamp(2rem,5vw,4rem)]">
  Smoothly scales with viewport
</h1>
11

暗色模式

启用暗色模式(class 策略)

默认 Tailwind 使用 prefers-color-scheme(media)。设置 darkMode:'class' 让你通过在父元素(通常是 <html>)添加 'dark' 类来切换暗色模式——主题切换器需要它。darkMode:'selector'(v3.4+)类似但支持自定义选择器。

tailwind
// tailwind.config.js
module.exports = {
  darkMode: "class",  // default is "media" (prefers-color-scheme)
  // ...
};

<!-- Toggle by adding/removing "dark" on <html> -->
<html class="dark">
  <body class="bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100">
    Auto-styled in dark
  </body>
</html>

Dark 变体

在任何实用类前加 dark: 前缀,使其仅在暗色模式生效。模式是先写亮色样式,再用 dark: 覆盖。要系统化:为每个 bg-*、text-*、border-* 都配 dark:* 等价物,确保暗色模式下不会出现破损。

tailwind
<div class="bg-white dark:bg-gray-800
            text-gray-900 dark:text-gray-100
            border-gray-200 dark:border-gray-700">
  Adapts to theme
</div>

<button class="bg-blue-600 dark:bg-blue-500
               hover:bg-blue-700 dark:hover:bg-blue-600">
  Themed button
</button>

主题切换脚本

将此内联脚本放在 <head> 中、页面渲染之前,以避免错误主题的闪烁(FOUC)。它先检查 localStorage,再回退到系统偏好。切换只是翻转类并持久化选择。

tailwind
// Check stored preference or system preference on load
if (localStorage.theme === 'dark' ||
    (!('theme' in localStorage) &&
     window.matchMedia('(prefers-color-scheme: dark)').matches)) {
  document.documentElement.classList.add('dark');
} else {
  document.documentElement.classList.remove('dark');
}

// Toggle button handler
function toggleTheme() {
  document.documentElement.classList.toggle('dark');
  localStorage.theme = document.documentElement.classList.contains('dark')
    ? 'dark' : 'light';
}

仅跟随系统偏好

如果不需要手动切换,darkMode:'media'(默认值)无需 JavaScript 即可跟随用户的系统设置。更简单,但失去了覆盖偏好的能力。适用于尊重系统选择即足够的内容站点。

tailwind
// tailwind.config.js
module.exports = {
  darkMode: "media",  // follow prefers-color-scheme automatically
  // ...
};

<!-- dark: utilities apply when OS is in dark mode -->
<div class="bg-white dark:bg-gray-900">
  No toggle, just follows the OS
</div>

<!-- Force a specific theme by not using dark: at all
     (the dark styles simply never apply) -->

暗色模式最佳实践

好的暗色模式不是简单反色:背景用深灰(gray-900)而非纯黑,文字用灰白(gray-100)而非纯白,图片稍微调暗,阴影减弱或去除。饱和的品牌色在暗色模式下通常需要提亮(blue-600 -> blue-500)。

tailwind
<!-- Don't just invert — lower contrast and saturation -->
<div class="bg-white dark:bg-gray-900     <!-- not black -->
            text-gray-900 dark:text-gray-100 <!-- not pure white -->
            shadow-lg dark:shadow-none">     <!-- shadows look off in dark -->

<!-- Dim images slightly in dark mode -->
<img class="dark:opacity-90 dark:brightness-90" src="/photo.jpg" />

<!-- Reduce border intensity -->
<div class="border-gray-200 dark:border-gray-800">...</div>
12

动画与过渡

过渡

transition-{属性} 定义哪些属性参与动画;duration-{ms} 设置时长;ease-{in,out,in-out} 设置缓动函数。transition-colors 最常见(比 transition-all 更省性能)。务必在 hover:* 变化前加 transition,否则会瞬间跳变。

tailwind
<button class="bg-blue-500 hover:bg-blue-600
               transition-colors duration-200">
  Color transition
</button>

<div class="transition-all duration-300 ease-in-out
            hover:scale-105 hover:shadow-lg">
  Multi-property transition
</div>

<div class="transition-opacity duration-500 opacity-50 hover:opacity-100">
  Fade in on hover
</div>

过渡属性

为性能起见,优先使用具体过渡(transition-colors、transition-transform)而非 transition-all——all 会监视每个属性,可能造成卡顿。duration-* 使用 75/100/150/200/300/500/700/1000ms。ease-out 对 UI 元素出现感觉很自然。

tailwind
<div class="transition-none">No animation</div>
<div class="transition-colors">bg/text/border-color</div>
<div class="transition-opacity">opacity only</div>
<div class="transition-shadow">box-shadow only</div>
<div class="transition-transform">scale/rotate/translate</div>
<div class="transition-all">Everything (heaviest)</div>

<!-- Duration & easing -->
<div class="duration-150">150ms</div>
<div class="duration-700">700ms</div>
<div class="ease-linear">Linear</div>
<div class="ease-in">Accelerate</div>
<div class="ease-out">Decelerate</div>

内置动画

Tailwind 内置四种关键帧动画:spin(加载器)、ping(扩散通知点)、pulse(透明度淡入淡出——完美用于骨架屏)、bounce(俏皮)。自定义动画可在配置中定义关键帧,再用 animate-[name] 引用。

tailwind
<div class="animate-spin">Spinning loader</div>
<div class="animate-ping">Pulsing ping (notifications)</div>
<div class="animate-pulse">Fading pulse (skeleton loaders)</div>
<div class="animate-bounce">Bouncing arrow</div>

<!-- Skeleton loader pattern -->
<div class="animate-pulse bg-gray-200 rounded h-4 w-3/4"></div>
<div class="animate-pulse bg-gray-200 rounded h-4 w-1/2 mt-2"></div>

变换

scale-、rotate-、translate-、skew- 都可组合,并随 transition-transform 平滑动画。用 origin-{center,top,bottom-left,...} 改变变换原点。卡片悬停花样(缩放 + 轻微旋转 + 上浮)在保持微妙时显得高级。

tailwind
<div class="hover:scale-110 transition-transform">Grow on hover</div>
<div class="hover:rotate-3">Tilt on hover</div>
<div class="hover:-translate-y-1">Lift on hover</div>
<div class="hover:skew-y-3">Skew on hover</div>

<!-- Combined -->
<div class="hover:scale-105 hover:-translate-y-1 hover:rotate-1
            transition-transform duration-300">
  Card flourish
</div>

<!-- Origin -->
<div class="origin-top-left rotate-12">Rotated from corner</div>

通过配置自定义动画

在 theme.extend 中定义自定义关键帧和动画名称。animation 值是简写:'{名称} {时长} {缓动} {迭代}'。定义后,animate-{name} 即成为普通实用类。保持关键帧精简——它们会打包进你的 CSS。

tailwind
// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      keyframes: {
        wiggle: {
          "0%, 100%": { transform: "rotate(-3deg)" },
          "50%":      { transform: "rotate(3deg)" },
        },
      },
      animation: {
        wiggle: "wiggle 1s ease-in-out infinite",
      },
    },
  },
};

// Usage
<div class="animate-wiggle">Wiggling</div>
13

表单

输入框

标准输入框模式:w-full 全宽、内边距、边框、圆角,以及一个移除默认 outline 的焦点环。focus:border-transparent 隐藏原生焦点边框;focus:ring-2 绘制清晰的可访问焦点指示器。务必为禁用状态设置样式以保持清晰。

tailwind
<input type="text"
       class="w-full px-3 py-2 border border-gray-300 rounded-md
              focus:outline-none focus:ring-2 focus:ring-blue-500
              focus:border-transparent
              placeholder-gray-400 text-gray-900"
       placeholder="Enter your name" />

<input type="email" disabled
       class="opacity-50 cursor-not-allowed" />

<textarea class="w-full rounded-md border-gray-300" rows="4"></textarea>

复选框与单选框

复选框/单选框上的 text-{color} 设置选中颜色(底层使用 accent-color)。focus:ring-* 添加键盘焦点指示器。自定义开关使用 peer-* 模式配合隐藏的 checkbox 驱动样式,或使用 @tailwindcss/forms 等插件。

tailwind
<label class="flex items-center gap-2">
  <input type="checkbox" class="rounded border-gray-300
                                 text-blue-600 focus:ring-blue-500" />
  Accept terms
</label>

<label class="flex items-center gap-2">
  <input type="radio" name="plan"
         class="border-gray-300 text-blue-600 focus:ring-blue-500" />
  Free plan
</label>

<!-- Custom toggle switch -->
<button role="switch" aria-checked="false"
        class="relative w-11 h-6 rounded-full bg-gray-300
               peer-checked:bg-blue-600 transition-colors">
  <span class="absolute left-0.5 top-0.5 w-5 h-5 bg-white
               rounded-full transition-transform peer-checked:translate-x-5">
  </span>
</button>

Select 与选项

原生 <select> 的样式在跨浏览器上受限;要完全控制请使用自定义下拉组件或 Headless UI 等库。@tailwindcss/forms 插件为所有表单元素提供一致、易于主题化的基线——对表单密集的应用值得一装。

tailwind
<select class="w-full px-3 py-2 border border-gray-300 rounded-md
                bg-white text-gray-900 focus:ring-2 focus:ring-blue-500">
  <option value="">Choose...</option>
  <option value="us">United States</option>
  <option value="cn">China</option>
</select>

<!-- Multiple select -->
<select multiple class="h-32">
  <option>Tag 1</option>
  <option>Tag 2</option>
</select>

表单布局

space-y-4 是为表单行设置间距的最简洁方式——无需逐字段加外边距。每个输入框配合 <label class='block text-sm font-medium mb-1'> 保持一致的标签样式。包在 max-w-md 中以在桌面端保持表单宽度可读。

tailwind
<form class="space-y-4 max-w-md">
  <div>
    <label class="block text-sm font-medium text-gray-700 mb-1">
      Email
    </label>
    <input type="email" class="w-full ..." />
  </div>
  <div>
    <label class="block text-sm font-medium text-gray-700 mb-1">
      Password
    </label>
    <input type="password" class="w-full ..." />
  </div>
  <button type="submit" class="w-full bg-blue-600 text-white py-2 rounded">
    Sign in
  </button>
</form>

按钮

按钮应有 active:(按下)、disabled:(状态)和 focus:(键盘)变体——不只是 hover。active:bg-{更深} 提供物理反馈。disabled:opacity-50 disabled:cursor-not-allowed 是标准的禁用处理。各按钮变体保持一致高度(如 py-2)。

tailwind
<button class="bg-blue-600 hover:bg-blue-700 active:bg-blue-800
               text-white font-medium py-2 px-4 rounded-md
               transition-colors focus:outline-none
               focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
  Primary
</button>

<button class="bg-white border border-gray-300 hover:bg-gray-50
               text-gray-700 py-2 px-4 rounded-md transition-colors">
  Secondary
</button>

<button class="text-blue-600 hover:text-blue-800 hover:underline">
  Ghost link button
</button>

<button class="bg-red-600 hover:bg-red-700 disabled:opacity-50
               disabled:cursor-not-allowed" disabled>
  Disabled
</button>
14

卡片

基础卡片

经典卡片:rounded + shadow + overflow-hidden(让图片圆角裁剪得漂亮)。图片上 object-cover 防止变形。hover:shadow-lg 配合 transition-shadow 给出上浮效果。overflow-hidden 是顶部圆角图片的关键。

tailwind
<div class="max-w-sm rounded-xl shadow-md overflow-hidden
            bg-white hover:shadow-lg transition-shadow">
  <img class="w-full h-48 object-cover" src="/photo.jpg" alt="" />
  <div class="p-6">
    <h3 class="text-xl font-semibold mb-2">Card title</h3>
    <p class="text-gray-600">Card description goes here.</p>
    <button class="mt-4 text-blue-600 font-medium hover:underline">
      Learn more
    </button>
  </div>
</div>

卡片网格

卡片网格使用 auto-fill + minmax 模式:卡片至少 280px 并拉伸填满,自动换行——无需媒体查询。对于已知断点上的固定列数,响应式 grid-cols-* 方案更易理解。

tailwind
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3
            gap-6">
  <div class="rounded-xl shadow p-6 bg-white">Card 1</div>
  <div class="rounded-xl shadow p-6 bg-white">Card 2</div>
  <div class="rounded-xl shadow p-6 bg-white">Card 3</div>
  <div class="rounded-xl shadow p-6 bg-white">Card 4</div>
</div>

<!-- Auto-fit grid for variable width -->
<div class="grid gap-6
            grid-cols-[repeat(auto-fill,minmax(280px,1fr))]">
  <!-- Cards naturally wrap based on viewport -->
</div>

可交互卡片(整张可点击)

将整张卡片包在 <a> 中使其完全可点击(比单独的『阅读更多』按钮体验更好)。group + group-hover 模式让你在父元素悬停时为子元素(标题颜色、箭头位置)加动画——对交互式卡片非常强大。

tailwind
<a href="/post" class="group block max-w-sm rounded-xl
         shadow-md hover:shadow-xl transition-shadow bg-white">
  <div class="p-6">
    <h3 class="font-semibold group-hover:text-blue-600 transition-colors">
      Card title
    </h3>
    <p class="text-gray-600 mt-2">Description...</p>
    <span class="mt-4 inline-flex items-center text-blue-600">
      Read more
      <svg class="w-4 h-4 ml-1 group-hover:translate-x-1 transition-transform">
        <!-- arrow icon path -->
      </svg>
    </span>
  </div>
</a>

带页脚的卡片

在卡片上用 flex flex-col、内容区用 flex-1,即使卡片正文长度不同也能让页脚固定在底部——保持一行卡片对齐。页脚通常包含元数据和操作,配以柔和背景和上边框。

tailwind
<div class="max-w-sm rounded-xl shadow bg-white flex flex-col">
  <div class="p-6 flex-1">
    <h3 class="text-lg font-semibold">Title</h3>
    <p class="text-gray-600 mt-2">Body content...</p>
  </div>
  <div class="px-6 py-4 bg-gray-50 border-t border-gray-100
              flex justify-between items-center">
    <span class="text-sm text-gray-500">Aug 12, 2025</span>
    <button class="text-sm text-blue-600 hover:underline">Share</button>
  </div>
</div>

个人资料 / 头像卡片

头像 + 姓名 + 操作是标准的行卡片模式。用 flex items-center gap-4 对齐。状态点用 absolute 定位在右下,ring 与卡片背景色匹配以『切出』小圆点。头像用 rounded-full + 相等的 w/h + object-cover。

tailwind
<div class="flex items-center gap-4 p-4 rounded-xl shadow bg-white">
  <img src="/avatar.jpg"
       class="w-12 h-12 rounded-full object-cover" alt="" />
  <div class="flex-1">
    <p class="font-semibold">Alice Zhang</p>
    <p class="text-sm text-gray-500">Software Engineer</p>
  </div>
  <button class="text-blue-600 text-sm font-medium">Follow</button>
</div>

<!-- Status indicator -->
<div class="relative">
  <img class="w-10 h-10 rounded-full" src="/avatar.jpg" />
  <span class="absolute bottom-0 right-0 w-3 h-3
               bg-green-500 rounded-full ring-2 ring-white"></span>
</div>
16

布局模式

定位

relative + absolute 是主力:在父元素上设 position:relative,子元素上设 position:absolute 以精确放置。inset-0 = top/right/bottom/left:0(填满父元素)。sticky top-0 是粘性表头的关键——需要父元素足够高才能滚动。

tailwind
<div class="static">Default flow</div>
<div class="relative">
  <div class="absolute top-0 right-0">Top-right of parent</div>
</div>
<div class="fixed bottom-4 right-4">Stuck to viewport</div>
<div class="sticky top-0">Sticks when scrolling</div>

<!-- Inset shorthand for all sides -->
<div class="absolute inset-0">Fills parent</div>
<div class="absolute inset-x-0 bottom-0">Full width, at bottom</div>

Z-Index 与层叠

Tailwind 提供 z-0/10/20/30/40/50 以及 z-auto。使用一致的约定:0 = 基础层、10 = 下拉、20 = 粘性表头、30 = 模态框、40 = 遮罩、50 = 提示/toast。模态框需要高 z-index 和 fixed inset-0 才能覆盖视口。

tailwind
<div class="z-0">Base layer</div>
<div class="z-10">Dropdowns</div>
<div class="z-20">Sticky headers</div>
<div class="z-30">Modals</div>
<div class="z-40">Overlays</div>
<div class="z-50">Tooltips, toasts</div>

<!-- Combine with relative/absolute/fixed -->
<div class="fixed inset-0 z-50 bg-black/50">Modal overlay</div>

显示

block/inline-block/inline/hidden 是基础。inline-block 适用于需要 width/height 但又要内联显示的元素。hidden 完全从布局中移除(而 opacity-0 保留空间)。用断点前缀切换实现响应式显示/隐藏。

tailwind
<div class="block">Full-width block</div>
<div class="inline-block">Inline with set width/height</div>
<div class="inline">Flows inline</div>
<div class="hidden">Removed from layout</div>
<div class="flex">Flex container</div>
<div class="grid">Grid container</div>

<!-- Toggle on breakpoint -->
<div class="hidden md:block">Hidden on mobile</div>
<div class="block md:hidden">Hidden on desktop</div>

<!-- Tables, contents, list-item also available -->

溢出

overflow-hidden 裁剪内容(也用于让圆角裁剪子元素)。overflow-auto 仅在需要时添加滚动条;overflow-x-auto 配合 whitespace-nowrap 是导航行和代码块横向滚动的标准模式。

tailwind
<div class="overflow-hidden">Clips overflow</div>
<div class="overflow-auto">Scrollbars if needed</div>
<div class="overflow-scroll">Always scrollable</div>
<div class="overflow-visible">Default, overflows</div>

<!-- Per-axis -->
<div class="overflow-x-auto whitespace-nowrap">Horizontal scroll</div>
<div class="overflow-y-auto h-64">Vertical scroll area</div>

<!-- Hide scrollbars while keeping scroll (Webkit) -->
<div class="overflow-x-auto scrollbar-hide">...</div>

浮动与清除

浮动已在很大程度上被 flexbox/grid 取代,但 float-left + mr-4 仍适用于文字围绕图片。对大多数图片尺寸需求,在设定尺寸的 img 上用 object-cover(填充,可能裁剪)或 object-contain(适配,可能留白)是现代做法。

tailwind
<img class="float-left mr-4 rounded" src="/photo.jpg" />
<p>Text wraps around the floated image on the right...</p>
<p class="clear-both">After the float</p>

<!-- Floats are mostly legacy; prefer flex/grid for layout.
     Still useful for text wrapping around images. -->

<!-- Object fit for responsive images -->
<img class="w-full h-48 object-cover" src="/hero.jpg" />
<img class="w-24 h-24 object-contain" src="/logo.png" />
17

效果与滤镜

背景模糊(毛玻璃)

backdrop-blur-* 模糊元素背后的内容(不是元素本身)——配合半透明背景(bg-white/30)产生毛玻璃效果。非常适合模态框、内容上方的粘性表头和 iOS 风格的磨砂面板。

tailwind
<div class="backdrop-blur-md bg-white/30 border border-white/20
            rounded-xl p-6 shadow-lg">
  Frosted glass card
</div>

<!-- Strengths -->
<div class="backdrop-blur-sm">Light blur</div>
<div class="backdrop-blur-md">Medium</div>
<div class="backdrop-blur-xl">Heavy</div>
<div class="backdrop-blur-2xl">Maximum</div>

<!-- Modal overlay with blur -->
<div class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50">
  Overlay with frosted bg
</div>

图片滤镜

滤镜实用类映射到 CSS filter 函数:blur、brightness、contrast、grayscale、invert、sepia、saturate、hue-rotate。grayscale hover:grayscale-0 模式是团队照和产品图的流行效果——悬停时显现色彩。

tailwind
<img class="blur-sm" src="/photo.jpg" />
<img class="blur-md" src="/photo.jpg" />
<img class="brightness-110" src="/photo.jpg" />
<img class="contrast-125" src="/photo.jpg" />
<img class="grayscale" src="/photo.jpg" />
<img class="invert" src="/photo.jpg" />
<img class="sepia" src="/photo.jpg" />
<img class="saturate-150" src="/photo.jpg" />

<!-- Combined + hover -->
<img class="grayscale hover:grayscale-0 transition-all duration-500"
     src="/photo.jpg" />

混合模式

mix-blend-mode 控制元素如何与背后的内容混合。在图片上的白色文字使用 mix-blend-difference 会产生高对比效果,无论底层图片如何都可读——hero 区常用。慎用;会显得花哨。

tailwind
<div class="mix-blend-multiply">Multiplies with bg</div>
<div class="mix-blend-screen">Lightens</div>
<div class="mix-blend-overlay">Contrast blend</div>
<div class="mix-blend-difference">Inverts colors</div>

<!-- Text over image with blend -->
<div class="relative">
  <img src="/photo.jpg" />
  <h1 class="absolute inset-0 flex items-center justify-center
             text-white mix-blend-difference text-6xl font-bold">
    Overlay text
  </h1>
</div>

透明度

opacity-{0,25,50,75,100}(还有 5/10/20/.../95)设置元素透明度——影响元素及其子元素。仅需半透明背景时改用 bg-{color}/{透明度},可保持文字完全不透明。opacity-0 隐藏但保留布局(而 hidden 则移除)。

tailwind
<div class="opacity-100">Fully visible</div>
<div class="opacity-75">75%</div>
<div class="opacity-50">Half</div>
<div class="opacity-25">Mostly transparent</div>
<div class="opacity-0">Invisible (still takes space)</div>

<!-- Hover fade -->
<button class="opacity-100 hover:opacity-80 transition-opacity">
  Fades on hover
</button>

<!-- vs bg-black/50: opacity affects the whole element
     (including children), bg color/opacity only the background -->

光标与用户选择

始终让光标匹配行为:cursor-pointer 用于可点击,cursor-not-allowed 用于禁用。select-none 禁用文本选择(适用于 UI 装饰和易双击的按钮)。在希望布局一致时,resize-none 阻止文本框的默认缩放手柄。

tailwind
<button class="cursor-pointer">Pointer on hover</button>
<div class="cursor-not-allowed opacity-50">Disabled</div>
<div class="cursor-move">Drag handle</div>
<div class="cursor-text">Text input area</div>

<!-- Selection -->
<p class="select-none">Cannot be selected</p>
<p class="select-text">Selectable text</p>
<p class="select-all">Selects all on click</p>

<!-- Resize handle -->
<textarea class="resize-none"></textarea>
<textarea class="resize-y"></textarea>
18

过渡与变换

变换原点与缩放

origin-* 设置变换原点。scale-x-* / scale-y-* 按轴独立缩放。transform-gpu 强制 GPU 加速(translate3d)以获得更平滑的动画——在轮播等变换密集元素出现卡顿时使用。

tailwind
<div class="origin-center scale-110">Center origin (default)</div>
<div class="origin-top-left scale-90">Top-left origin</div>
<div class="origin-bottom rotate-45">Bottom origin, rotated</div>

<!-- Combined transforms -->
<div class="transform-gpu hover:scale-105 hover:rotate-3
            transition-transform duration-300">
  GPU-accelerated flourish
</div>

<!-- Independent scale axes -->
<div class="hover:scale-x-110">Stretches horizontally</div>
<div class="hover:scale-y-90">Squishes vertically</div>

平移与旋转

translate-{x,y}-{n} 用间距标尺移动元素(或用 -translate-x-1/2 表示 50%)。left-1/2 + -translate-x-1/2 模式可让绝对定位元素无论宽度如何都完美居中——对工具提示和模态框很有用。

tailwind
<div class="translate-x-4">16px right</div>
<div class="-translate-x-4">16px left</div>
<div class="translate-y-2">8px down</div>
<div class="rotate-45">45deg clockwise</div>
<div class="-rotate-12">12deg counter-clockwise</div>
<div class="rotate-180">Flipped</div>

<!-- Centering trick: absolute + translate -->
<div class="absolute left-1/2 top-1/2
            -translate-x-1/2 -translate-y-1/2">
  Perfectly centered
</div>

倾斜与 3D 变换

skew 沿轴倾斜元素——适用于微妙的平行四边形效果。3D 变换(perspective、rotate-y、rotate-x、transform-style-3d)在默认 Tailwind 中需主题扩展,但可实现翻卡和视差效果。多数项目只用 2D 变换。

tailwind
<div class="skew-x-12">Skewed horizontally</div>
<div class="skew-y-6">Skewed vertically</div>
<div class="-skew-x-6">Counter skew</div>

<!-- 3D (needs perspective on parent) -->
<div class="perspective-1000">
  <div class="rotate-y-12 transform-style-3d">Tilted in 3D</div>
</div>

<!-- Card flip pattern -->
<div class="preserve-3d group hover:rotate-y-180
            transition-transform duration-700">
  Flips on hover (needs config)
</div>

过渡延迟与计时

delay-{ms} 延迟过渡开始——结合逐子元素延迟创建错落入场(每个项目稍晚启动)。ease-out 对元素出现感觉很自然(减速就位),ease-in 对消失很自然(加速离开)。

tailwind
<div class="transition-colors duration-300 delay-150
            hover:bg-blue-500">
  Starts after 150ms
</div>

<!-- Stagger children via inline delay style -->
<div class="flex gap-2">
  <div class="transition-all delay-0 duration-500">A</div>
  <div class="transition-all delay-100 duration-500">B</div>
  <div class="transition-all delay-200 duration-500">C</div>
</div>

<!-- Easing -->
<div class="ease-in-out">Smooth</div>
<div class="ease-out">Decelerate (good for entrances)</div>
<div class="ease-in">Accelerate (good for exits)</div>

Hover vs Focus vs Active 状态

除 hover 外,始终考虑 focus(键盘用户)和 active(鼠标按下)。focus-visible: 仅在键盘聚焦时应用(非鼠标点击)——通常是焦点环所期望的。配合 focus:outline-none 抑制默认浏览器环。group + group-hover: 让父级悬停驱动子级样式——对卡片和复杂悬停至关重要。

tailwind
<button class="bg-blue-500
               hover:bg-blue-600   <!-- mouse over -->
               focus:bg-blue-700   <!-- keyboard focus -->
               active:bg-blue-800  <!-- mouse down -->
               focus:outline-none focus:ring-2 focus:ring-blue-300
               transition-colors">
  All states styled
</button>

<!-- Group hover: style children when parent hovered -->
<div class="group">
  <button class="group-hover:scale-110 transition-transform">
    Scales when parent hovered
  </button>
</div>
19

尺寸

宽度标尺

w-* 使用间距标尺加分数(1/2、1/3、2/3、1/4、3/4、1/5、...、1/12)表示百分比。w-full = 100%,w-screen = 100vw,w-fit = 内在宽度,w-max = max-content。用 w-full + max-w-{size} 让响应式内容限制在可读宽度。

tailwind
<div class="w-0">0</div>
<div class="w-px">1px</div>
<div class="w-1">0.25rem</div>
<div class="w-4">1rem (16px)</div>
<div class="w-16">4rem (64px)</div>
<div class="w-64">16rem</div>
<div class="w-96">24rem</div>

<!-- Fractions -->
<div class="w-1/2">50%</div>
<div class="w-1/3">33.33%</div>
<div class="w-2/3">66.67%</div>
<div class="w-full">100%</div>
<div class="w-screen">100vw</div>

高度与视口

h-screen = 100vh,在移动浏览器有地址栏问题。移动端友好的全高布局优先用 h-dvh(动态视口高度)——它会随浏览器 UI 显隐而调整。min-h-screen 是粘性页脚布局的标准。

tailwind
<div class="h-8">2rem</div>
<div class="h-64">16rem</div>
<div class="h-full">100% of parent</div>
<div class="h-screen">100vh (full viewport)</div>

<!-- Modern viewport units (v3.4+) -->
<div class="h-dvh">Dynamic viewport height (mobile-friendly)</div>
<div class="h-svh">Small viewport height</div>
<div class="h-lvh">Large viewport height</div>

<!-- min/max -->
<div class="min-h-screen">At least viewport tall</div>
<div class="max-h-96 overflow-y-auto">Capped scroll area</div>

最小/最大宽度

max-w-{xs,sm,md,lg,xl,2xl,...,7xl} 映射到适合内容宽度的 rem 尺寸。将页面内容包在 max-w-7xl mx-auto 中是标准做法。min-w-0 是关键的 flexbox 技巧——它让 flex 子元素能缩小到内在尺寸以下以防止溢出。

tailwind
<!-- Max-width is the key to readable content -->
<article class="max-w-2xl mx-auto">
  Caps article at ~42rem (readable line length)
</article>

<!-- Common max-widths -->
<div class="max-w-sm">384px</div>
<div class="max-w-md">28rem</div>
<div class="max-w-lg">32rem</div>
<div class="max-w-xl">36rem</div>
<div class="max-w-7xl">80rem</div>

<!-- min-width for inputs etc -->
<input class="min-w-0" />  <!-- prevent flex overflow -->
<div class="min-w-full">Always at least full width</div>

宽高比

aspect-{ratio} 无论宽度如何都保持固定宽高比——比旧的 padding-bottom hack 干净得多。aspect-video 是视频嵌入的标准。配合 object-cover 可在无变形的情况下填满盒子。aspect-[21/9] 等任意比例也可用。

tailwind
<div class="aspect-square">1:1 square</div>
<div class="aspect-video">16:9 widescreen</div>
<div class="aspect-[4/3]">4:3</div>
<div class="aspect-[21/9]">Ultrawide</div>

<!-- Responsive video embed -->
<div class="aspect-video w-full">
  <iframe class="w-full h-full" src="..."></iframe>
</div>

<!-- Avatar / product image -->
<img class="aspect-square object-cover w-24" />

对象适配与定位

<img>(及 <video>)上的 object-fit 控制源如何填充盒子:cover(填充,裁剪)、contain(适配,留白)、fill(拉伸)、none(原始尺寸)。配合 object-{position} 控制裁剪时保留哪部分。object-cover + object-center 是 hero 图的默认选择。

tailwind
<img class="w-full h-48 object-cover" src="/hero.jpg" />
<!-- Fills the box, may crop. Best for hero images. -->

<img class="w-full h-48 object-contain" src="/logo.png" />
<!-- Fits entire image, may letterbox. Best for logos. -->

<img class="w-full h-48 object-fill" src="/img.jpg" />
<!-- Stretches to fill (distorts). Rarely what you want. -->

<img class="w-full h-48 object-none" src="/img.jpg" />
<!-- Keeps original size, may overflow. -->

<!-- Position -->
<img class="object-cover object-top" src="/portrait.jpg" />
<img class="object-cover object-center" src="/photo.jpg" />
20

交互与状态

Hover、Focus 与 Group

group 将元素标记为状态源;group-hover:* 在父元素悬停时为子元素应用样式。对悬停卡片同时影响图片、标题和隐藏操作的卡片至关重要。命名分组(group/card)允许嵌套。

tailwind
<button class="hover:bg-blue-600">Hover state</button>
<input class="focus:ring-2 focus:ring-blue-500" />
<div class="active:scale-95">Press feedback</div>

<!-- group / group-hover: style children based on parent state -->
<div class="group">
  <img class="group-hover:scale-110 transition-transform" />
  <h3 class="group-hover:text-blue-600">Title</h3>
  <p class="opacity-0 group-hover:opacity-100">Revealed on hover</p>
</div>

Peer(兄弟状态)

peer 将元素标记为其兄弟元素(默认仅后续兄弟)的状态源。peer-checked:* 让你基于复选框/单选框状态为兄弟元素设置样式——可在无 JavaScript 的情况下实现纯 CSS 切换、密码显示按钮和手风琴。

tailwind
<!-- Style a sibling based on an input's state -->
<input type="checkbox" id="c" class="peer" />
<label for="c" class="peer-checked:text-blue-600">
  Styled when checkbox checked
</label>

<!-- Show/hide password -->
<input type="checkbox" id="show" class="peer hidden" />
<label for="show" class="peer-checked:hidden">Show</label>
<label for="show" class="hidden peer-checked:inline">Hide</label>

<!-- Toggle a panel -->
<input type="checkbox" class="peer hidden" />
<div class="hidden peer-checked:block">Toggleable panel</div>

Focus-Visible(仅键盘)

焦点环用 focus-visible: 而非 focus:——它只对键盘用户显示环(他们需要环),对鼠标点击隐藏(鼠标点击有自己的视觉反馈)。配合 focus:outline-none 抑制默认浏览器环。

tailwind
<button class="focus:outline-none
               focus-visible:ring-2 focus-visible:ring-blue-500">
  No ring on mouse click, ring on keyboard focus
</button>

<!-- Why focus-visible: -->
<!-- - focus: applies on BOTH mouse click and keyboard
     (annoying for mouse users)
   - focus-visible: only on keyboard navigation
     (the accessible choice for focus rings) -->

占位符与文件输入

placeholder-* 设置占位符文本样式。file:* 设置 <input type='file'> 内部伪按钮的样式——这个元素出了名地难以样式化,但 Tailwind 的 file: 变体使其变得可控。上面的模式可给出干净、带品牌的文件上传按钮。

tailwind
<input class="placeholder-gray-400 placeholder-italic"
       placeholder="Type here..." />

<!-- Style the file input button -->
<input type="file"
       class="block w-full text-sm text-gray-500
              file:mr-4 file:py-2 file:px-4
              file:rounded-md file:border-0
              file:text-sm file:bg-blue-50
              file:text-blue-700
              hover:file:bg-blue-100" />

Marker 与 Selection

marker:* 设置列表项目符号/编号样式。selection:* 设置用户选择文本时的高亮。first-letter:* / first-line:* 实现首字下沉和小型大写首行——适用于编辑设计。所有这些伪元素都有专用的 Tailwind 变体。

tailwind
<ul class="marker:text-blue-500 list-disc pl-5">
  <li>Blue bullet</li>
  <li>Blue bullet</li>
</ul>

<!-- Style text selection -->
<p class="selection:bg-blue-200 selection:text-blue-900">
  Select this text to see a blue highlight.
</p>

<!-- Global selection (in CSS) -->
::selection { background: #bfdbfe; color: #1e3a8a; }

<!-- First-line / first-letter -->
<p class="first-letter:text-5xl first-letter:font-bold
          first-letter:float-left first-letter:mr-2
          first-line:uppercase first-line:tracking-wide">
  Drop cap paragraph.
</p>
21

任意值与自定义

任意值

方括号让你无需扩展主题即可使用任何 CSS 值——非常适合一次性场景。值中的下划线会变成空格(所以 grid-cols-[200px_1fr] 变成 '200px 1fr')。过度使用会导致设计不一致;重复值优先用主题扩展。

tailwind
<!-- Any CSS value in square brackets -->
<div class="w-[300px] h-[200px] bg-[#1da1f2]">
  Custom sizes and colors
</div>

<p class="text-[13px] leading-[1.6]">
  Custom typography
</p>

<div class="grid-cols-[200px_1fr_100px]">
  Custom grid template (underscores = spaces)
</div>

<div class="top-[117px]">
  Custom positioning
</div>

任意属性

[属性:值] 定义任意 CSS 属性——适用于 Tailwind 没有实用类的属性(mask-type、hyphens 等)。[--var:值] 设置一个 CSS 变量,之后可在任意值中引用,如 p-[var(--tw)]。对主题化很强大。

tailwind
<!-- Define an arbitrary CSS property -->
<div class="[mask-type:luminance]">
  Sets mask-type: luminance
</div>

<!-- Arbitrary property with Tailwind variable -->
<div class="[--scroll-offset:56px] top-[var(--scroll-offset)]">
  Custom CSS variable
</div>

<!-- CSS variables + arbitrary values are powerful together -->
<div class="[--tw:1rem] p-[var(--tw)]">
  Theme-driven custom value
</div>

任意变体

任意变体扩展 Tailwind 的变体系统:min-[1200px]: 用于自定义断点,aria-*: 用于 ARIA 状态,odd:/even: 用于斑马纹,has-[:checked]: 用于关系样式。has-* 变体(最近的 CSS 特性)在基于子元素状态样式化父元素时特别强大。

tailwind
<!-- Arbitrary media query -->
<div class="min-[1200px]:flex">Custom breakpoint</div>

<!-- ARIA attribute variants -->
<button aria-pressed="true"
        class="aria-pressed:bg-blue-600">
  Toggle styled by ARIA state
</button>

<!-- nth-child -->
<li class="odd:bg-gray-50">Striped table row</li>
<li class="even:bg-white">Striped table row</li>

<!-- has: variant (Tailwind v3.4+) -->
<div class="has-[:checked]:bg-blue-50">
  Highlights when it contains a checked input
</div>

主题扩展

theme.extend 添加到默认值;theme.{key} 会替换它们。DEFAULT 让你使用基础名(bg-brand)加色阶(bg-brand-dark)。添加自定义间距、断点、圆角等。几乎总是应该用 extend——替换调色板会移除 Tailwind 的默认值。

tailwind
// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      colors: {
        brand: { light: "#5eead4", DEFAULT: "#14b8a6", dark: "#0f766e" },
      },
      spacing: { 18: "4.5rem" },
      borderRadius: { xl: "1rem" },
      screens: { tall: { raw: "(min-height: 800px)" } },
    },
  },
};

<!-- Now you can use: -->
<div class="bg-brand text-brand-light p-18 rounded-xl">
  Custom themed utilities
</div>

插件与 @apply

插件添加新的实用类或组件(forms、typography、aspect-ratio 是官方的)。@apply 让你将 Tailwind 实用类内联到自定义 CSS 中——当你有几十处相同使用的类时很有用。不要过度使用 @apply;实用优先的方式通常更干净。

tailwind
// tailwind.config.js — register a plugin
const forms = require("@tailwindcss/forms");
module.exports = { plugins: [forms] };

/* Use @apply to compose utilities into custom CSS */
@layer components {
  .btn-primary {
    @apply bg-blue-600 text-white font-medium py-2 px-4
           rounded-md hover:bg-blue-700 transition-colors;
  }
}

<!-- Then use the custom class -->
<button class="btn-primary">Save</button>
22

实战模式

模态框 / 对话框

模态框解剖:fixed inset-0 遮罩(覆盖视口)、z-50(在所有内容之上)、flex 居中放置面板,面板本身 relative 定位以位于遮罩之上。backdrop-blur 增添质感。务必提供可见的关闭按钮和 ESC 关闭以支持可访问性。

tailwind
<div class="fixed inset-0 z-50 flex items-center justify-center">
  <!-- Overlay -->
  <div class="absolute inset-0 bg-black/50 backdrop-blur-sm"></div>
  <!-- Panel -->
  <div class="relative bg-white rounded-xl shadow-2xl
              w-full max-w-md mx-4 p-6">
    <h2 class="text-lg font-semibold mb-4">Modal title</h2>
    <p class="text-gray-600">Modal body content.</p>
    <div class="flex justify-end gap-2 mt-6">
      <button class="px-4 py-2 text-gray-600">Cancel</button>
      <button class="px-4 py-2 bg-blue-600 text-white rounded-md">OK</button>
    </div>
  </div>
</div>

Toast / 通知

Toast 固定在某个角落(右下为惯例),限制宽度,左边框颜色表示类型(绿=成功、红=错误、黄=警告、蓝=信息)。配合 JS 驱动的动画(通过 translate-x 滑入),并在几秒后自动消失。

tailwind
<div class="fixed bottom-4 right-4 z-50 max-w-sm
            bg-white rounded-lg shadow-xl border-l-4 border-green-500
            flex items-center gap-3 p-4">
  <div class="text-green-500">
    <svg class="w-5 h-5"><!-- check icon --></svg>
  </div>
  <div class="flex-1">
    <p class="font-medium text-gray-900">Saved successfully</p>
    <p class="text-sm text-gray-500">Your changes are live.</p>
  </div>
  <button class="text-gray-400 hover:text-gray-600">×</button>
</div>

徽章与胶囊

徽章是 inline-flex 的胶囊(rounded-full)或标签(rounded)。用 bg-{color}-100 + text-{color}-800 实现柔和粉彩风格。加一个点(w-1.5 h-1.5 rounded-full)作为状态指示。徽章文本保持 text-xs font-medium。

tailwind
<span class="inline-flex items-center px-2.5 py-0.5
             rounded-full text-xs font-medium
             bg-green-100 text-green-800">
  Active
</span>

<span class="inline-flex items-center gap-1 px-2 py-0.5
             rounded-full text-xs font-medium
             bg-blue-100 text-blue-800">
  <span class="w-1.5 h-1.5 rounded-full bg-blue-500"></span>
  Online
</span>

<span class="inline-flex items-center px-2 py-0.5
             rounded text-xs font-medium
             bg-red-100 text-red-800">
  Deprecated
</span>

空状态

空状态需要:柔和圆圈中的图标、简短标题、辅助文本和一个主要 CTA。一切居中(text-center mx-auto),使用充足的 py-12 内边距,并降低颜色饱和度(gray-400/500 文本),让 CTA 按钮吸引视线。不要只显示『无数据』。

tailwind
<div class="text-center py-12 px-4">
  <div class="mx-auto w-16 h-16 rounded-full bg-gray-100
              flex items-center justify-center mb-4">
    <svg class="w-8 h-8 text-gray-400"><!-- icon --></svg>
  </div>
  <h3 class="text-lg font-medium text-gray-900">No items yet</h3>
  <p class="mt-1 text-sm text-gray-500">
    Get started by creating your first item.
  </p>
  <button class="mt-4 bg-blue-600 text-white px-4 py-2 rounded-md">
    New item
  </button>
</div>

加载骨架屏

骨架屏在容器上使用 animate-pulse,内部放置形状类似真实内容的灰色块。匹配加载后状态的布局和比例,以便数据到来时不会有突兀的跳动。rounded-full + w-10 h-10 模仿头像;不同宽度(w-3/4、w-1/2)模仿文本行。

tailwind
<div class="animate-pulse space-y-3">
  <div class="h-4 bg-gray-200 rounded w-3/4"></div>
  <div class="h-4 bg-gray-200 rounded w-1/2"></div>
  <div class="space-y-2">
    <div class="h-3 bg-gray-200 rounded"></div>
    <div class="h-3 bg-gray-200 rounded"></div>
  </div>
  <div class="flex gap-4">
    <div class="w-10 h-10 bg-gray-200 rounded-full"></div>
    <div class="flex-1 space-y-2 py-1">
      <div class="h-3 bg-gray-200 rounded"></div>
      <div class="h-3 bg-gray-200 rounded w-5/6"></div>
    </div>
  </div>
</div>

这篇内容对您有帮助吗?

学习路径

从零开始学习

通过结构化课程从头学习这个语言。