Tailwind需手动配置@keyframes和animation才能使用自定义加载动画;animate-spin可组合工具类调速、换色、缩放;animate-pulse仅适用于骨架屏占位,不可替代旋转加载指示器。

用 @keyframes 配合 animate- 类名写自定义加载动画
Tailwind 默认不提供加载动画(如旋转、脉冲、骨架屏),必须手动注入 CSS 动画帧。直接在 tailwind.config.js 的 theme.extend.animation 和 theme.extend.keyframes 中定义,才能用 animate-spin 这类类名。
常见错误是只写 @keyframes 但没注册进配置,结果类名无效;或动画名拼写不一致(比如定义了 spin-slow 却写成 animate-spin-slowly)。
- 在
tailwind.config.js的theme.extend下添加:
keyframes: {
'spin-slow': {
'0%': { transform: 'rotate(0deg)' },
'100%': { transform: 'rotate(360deg)' },
},
},
- 再注册动画名和时长/缓动:
animation: {
'spin-slow': 'spin-slow 2s linear infinite',
},
- HTML 中即可使用:
<div class="animate-spin-slow w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full"></div>
复用 animate-spin 但改颜色/大小/速度的快捷方式
默认 animate-spin 是 1s 线性无限旋转,想调速、换色或缩放,别重写整个动画——用 Tailwind 已有工具类组合更轻量。
- 改速度:加
duration-700(支持duration-75到duration-[2000])、ease-in-out - 改颜色:用
border-t-transparent配合border-r-blue-400等控制单边色,实现“缺口旋转”效果 - 改大小:直接设
w-4 h-4或text-xl(对 inline 元素生效) - 注意:
animate-spin本身不带尺寸或边框,必须显式加border和rounded-full才看得见
示例:<div class="animate-spin duration-1500 ease-linear w-5 h-5 border-2 border-purple-500 border-t-transparent rounded-full"></div>
立即学习“前端免费学习笔记(深入)”;
避免用 animate-pulse 做加载指示器
animate-pulse 是透明度渐变动画(opacity-0 → opacity-100),视觉上是“闪烁”,不是“进行中”信号。用户会误判状态是否已就绪,尤其在表单提交或 API 请求场景。
- 它适合提示“这里可能有新内容”,不适合表示“正在处理”
- 若强行用,需叠加其他视觉线索(如文字“加载中…”),否则可访问性差(屏幕阅读器无法感知 pulse)
- 真正需要进度感时,优先选旋转类动画,或搭配
bg-gray-200 animate-pulse做骨架屏占位,而非纯 pulse
骨架屏(skeleton screen)用 bg-gray-200 + animate-pulse 的实操要点
骨架屏本质是占位结构 + 脉冲动画模拟内容加载,关键不在动画本身,而在布局保形。
- 先用真实结构类(如
h-6 w-48、rounded-lg)搭出卡片/头像/段落的轮廓 - 再统一加
bg-gray-200 animate-pulse,不要每个元素单独设不同背景色 - 动画要加在父容器上(如
<div class="animate-pulse">...</div>),否则子元素 pulse 不同步,看起来像抖动 - 响应式下记得用
md:bg-gray-100等断点覆盖,避免深色模式下骨架不可见
容易忽略的是:骨架屏应和真实内容 DOM 结构一致,否则 hydration 后布局跳动明显——尤其是 Next.js 或 React Server Components 场景。


















