Spinner 加载动画在按钮里显示不居中怎么办?

A. 洺华 阅读 37

我在用 Tailwind CSS 写一个带加载状态的提交按钮,但 Spinner 图标总是偏上,没法垂直居中。明明用了 flex items-center justify-center,可还是歪的。

这是我的代码:

<button disabled type="submit" class="flex items-center justify-center gap-2 px-4 py-2 bg-blue-500 text-white rounded">
  <svg class="animate-spin h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
  </svg>
  提交中...
</button>

试过加 align-middle、调 line-height,都没用,到底该怎么让它真正居中?

我来解答 赞 11 收藏
二维码
手机扫码查看
2 条解答
慕容俊美
这个问题我遇到过,其实是个小细节的问题。Tailwind的 flex items-center justify-center 已经在水平方向居中了,但垂直方向还是有点问题。

关键在于你的 svg 元素的高度和按钮文字的行高不完全一致。虽然都是4个单位高度,但字体渲染时会有一些细微差异。

可以优化成这样:
<button disabled type="submit" class="flex items-center justify-center gap-2 px-4 py-2 bg-blue-500 text-white rounded">
<span class="flex items-center">
<svg class="animate-spin h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
</span>
提交中...
</button>


给 svg 外包一层 span,并加上 flex items-center。这样能确保 svg 和文字都相对于按钮容器独立居中对齐。

记得检查一下你的 Tailwind 配置里 h-4 和文本大小是否匹配,必要时可以微调到 h-5 或 h-3。这招我在好几个项目里用过,效果不错。
点赞
2026-03-27 16:02
夏侯乙涵
给按钮加个 h-full,再给 svg 包一层 div 加 h-full flex items-center justify-center 就这样
<button disabled type="submit" class="flex items-center justify-center gap-2 px-4 py-2 bg-blue-500 text-white rounded h-full">
<div class="h-full flex items-center justify-center">
<svg class="animate-spin h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
</div>
提交中...
</button>
点赞
2026-03-27 04:05