Spinner 加载动画在按钮里显示不居中怎么办?
我在用 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,都没用,到底该怎么让它真正居中?
关键在于你的
svg元素的高度和按钮文字的行高不完全一致。虽然都是4个单位高度,但字体渲染时会有一些细微差异。可以优化成这样:
给 svg 外包一层 span,并加上 flex items-center。这样能确保 svg 和文字都相对于按钮容器独立居中对齐。
记得检查一下你的 Tailwind 配置里 h-4 和文本大小是否匹配,必要时可以微调到 h-5 或 h-3。这招我在好几个项目里用过,效果不错。
h-full,再给 svg 包一层 div 加h-full flex items-center justify-center就这样