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

Angular中如何将SpinKit加载Spinner居中显示在屏幕中央

解决Angular+Bootstrap中Spinner屏幕居中问题

嘿,我来帮你搞定这个Spinner居中的问题!你之前的Spinner只实现了水平居中,但没处理垂直方向,而且没有做全屏覆盖,所以会停在页面底部。结合Angular和Bootstrap,给你两个简单有效的方案:

方案一:自定义全屏覆盖层(纯CSS)

首先修改Spinner组件的HTML,给它套一个全屏的容器:

<div class="spinner-overlay">
  <div class="spinner">
    <div class="rect1"></div>
    <div class="rect2"></div>
    <div class="rect3"></div>
    <div class="rect4"></div>
    <div class="rect5"></div>
  </div>
</div>

然后更新CSS,添加覆盖层样式,并调整原Spinner的margin:

/* 全屏覆盖层:固定定位占满视口,flex布局实现居中 */
.spinner-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8); /* 可选:半透明白背景,增强加载感知 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999; /* 确保在所有内容之上 */
}

/* 原Spinner样式:去掉margin:100px auto,因为flex已经帮我们居中了 */
.spinner {
  width: 50px;
  height: 40px;
  text-align: center;
  font-size: 10px;
}

/* 以下保留你原来的Spinner动画样式 */
.spinner > div {
  background-color: #333;
  height: 100%;
  width: 6px;
  display: inline-block;
  -webkit-animation: sk-stretchdelay 1.2s infinite ease-in-out;
  animation: sk-stretchdelay 1.2s infinite ease-in-out;
}

.spinner .rect2 {
  -webkit-animation-delay: -1.1s;
  animation-delay: -1.1s;
}

.spinner .rect3 {
  -webkit-animation-delay: -1.0s;
  animation-delay: -1.0s;
}

.spinner .rect4 {
  -webkit-animation-delay: -0.9s;
  animation-delay: -0.9s;
}

.spinner .rect5 {
  -webkit-animation-delay: -0.8s;
  animation-delay: -0.8s;
}

@-webkit-keyframes sk-stretchdelay {
  0%, 40%, 100% { -webkit-transform: scaleY(0.4) }
  20% { -webkit-transform: scaleY(1.0) }
}

@keyframes sk-stretchdelay {
  0%, 40%, 100% {
    transform: scaleY(0.4);
    -webkit-transform: scaleY(0.4);
  } 20% {
    transform: scaleY(1.0);
    -webkit-transform: scaleY(1.0);
  }
}

方案二:利用Bootstrap工具类(更简洁)

既然你已经在用Bootstrap,直接用它的定位、布局工具类就能快速实现,不用写额外的自定义CSS:

修改Spinner组件的HTML:

<div class="position-fixed top-0 start-0 w-100 h-100 d-flex justify-content-center align-items-center bg-white bg-opacity-80 z-50">
  <div class="spinner">
    <div class="rect1"></div>
    <div class="rect2"></div>
    <div class="rect3"></div>
    <div class="rect4"></div>
    <div class="rect5"></div>
  </div>
</div>

然后只需要调整原Spinner的CSS,去掉margin: 100px auto即可,其他动画样式保留不变。

原理说明

  • position-fixed:让容器固定在视口,不随页面滚动移动
  • top-0 start-0 w-100 h-100:占满整个屏幕宽度和高度
  • d-flex justify-content-center align-items-center:flex布局,实现内部元素垂直水平居中
  • bg-white bg-opacity-80:可选半透明白背景,提升用户体验
  • z-50:Bootstrap的层级类,确保Spinner在其他内容之上

这两个方案都能完美解决你的问题,选哪个看你更倾向自定义还是用框架工具类~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 16:17:30