You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让加载Spinner始终居中?适配表格、按钮等多场景

实现加载Spinner在各类场景中居中的方案

核心问题分析

你的代码中.th-loader缺少必要的布局定位配置,导致Spinner无法与同级元素(如按钮)或在父容器(如表格单元格)内保持居中对齐,需要针对不同场景调整布局逻辑。

具体修改方案

1. 通用基础样式修正

先调整.th-loader和内部元素的样式,让Spinner能在容器内稳定居中,同时适配多种场景:

/* 修正后的完整CSS */
.th-loader {
  /* 行内flex适配按钮等行内元素,块级场景可改为flex */
  display: inline-flex;
  align-items: center;
  justify-content: center;
  position: relative;
  /* 可选:若需要覆盖同级元素,可设置与目标元素一致的宽高 */
  /* width: 80px;
  height: 32px; */
}

.th-loader .progress {
  /* 移除原top/left定位,依赖flex布局实现居中 */
  width: var(--loading-indicator-border);
  aspect-ratio: 1;
  background: #006edb;
  border-radius: 50%;
  transform: rotate(0deg) translateY(calc((var(--loading-indicator-size) * -0.5) + (var(--loading-indicator-border) * 0.5)));
  animation: spin 1s infinite linear;

  &.mini{
    --loading-indicator-size: 24px;
    --loading-indicator-border: 4px;
  }
}

@keyframes spin {
  to{transform: rotate(360deg) translateY(calc((var(--loading-indicator-size) * -0.5) + (var(--loading-indicator-border) * 0.5)))}
}

.th-loader .progress:after {
  position: absolute;
  content: '';
  width: var(--loading-indicator-size);
  aspect-ratio: 1;
  top: 50%;
  left: 50%;
  translate: -50% -50%; /* 双向居中,适配环形背景 */
  background: conic-gradient(transparent 10%, #006edb);
  border-radius: 50%;
  mask: radial-gradient(transparent calc(((var(--loading-indicator-size) * 0.5) - var(--loading-indicator-border)) - 1px), #006edb calc((var(--loading-indicator-size) * 0.5) - var(--loading-indicator-border)));
}

2. 分场景适配示例

场景一:按钮内替换文字居中显示

点击按钮后隐藏文字,显示居中Spinner:

<div>
  <button class="btn-loader">
    <span class="btn-text">Click Me</span>
    <div class="th-loader" style="display: none;">
      <div class="progress mini"></div>
    </div>
  </button>
</div>
.btn-loader {
  position: relative;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background: #006edb;
  color: #fff;
  cursor: pointer;
}
.btn-loader.loading .btn-text {
  display: none;
}
.btn-loader.loading .th-loader {
  display: inline-flex !important;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

场景二:表格单元格内全屏居中

让Spinner占满表格单元格高度并居中:

.table-cell .th-loader {
  display: flex;
  height: 60px; /* 或设置为100%占满单元格高度 */
}
<table border="1">
  <tr>
    <td class="table-cell">
      <div class="th-loader">
        <div class="progress mini"></div>
      </div>
    </td>
  </tr>
</table>

关键修改点总结

  • 给.th-loader添加flex/inline-flex布局,配合align-items和justify-content实现内部Spinner的基础居中。
  • 调整.progress:after的定位逻辑,确保环形背景与核心圆点同步居中。
  • 根据场景选择inline-flex(行内元素)或flex(块级容器),适配按钮、表格等不同使用场景。

内容的提问来源于stack exchange,提问作者parastoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 20:35:19