Font Awesome加载Spinner下方单行居中适配文本实现问题
解决Font Awesome Spinner 下方单行文本的居中自适应问题
我在测试Font Awesome的spinner组件时遇到了个小麻烦:想在图标下方加一行单行文本,还要兼容Bootstrap,但现在要么文本换行,要么设置宽度后没法和图标居中对齐,窗口变小时也不能自适应。
我当前的代码:
HTML
<div class="center-parent" id="spinner"> <div class="center-container"> <i class="fa fa-cog fa-spin"></i> <span class="spinner-text">Please wait while we gather data from wherever...</span> </div> </div>
CSS
.center-parent { position: absolute; top: 0; bottom: 0; left: 0; right: 0; width: 100%; height: 100%; z-index: -1; } .center-container { width: 0 auto; height: 0 auto; font-size: 40px; position: absolute; top: 50%; left: 50%; margin-top: -30px; margin-right: 0; margin-bottom: 0; margin-left: -30px; z-index: -1; } .spinner-text { margin: 0 auto; display: table; width: 100%; height: 0 auto; font-size: 20px; position: absolute; text-align: center; }
JavaScript
<script type="text/javascript"> var spinnerVisible = false; $(document).ready(function () { showSpinner() }); function showSpinner() { if (!spinnerVisible) { $("div#spinner").fadeIn("fast"); spinnerVisible = true; } setTimeout(hideSpinner, 4000); }; function hideSpinner() { if (spinnerVisible) { var spinner = $("div#spinner"); spinner.stop(); spinner.fadeOut("fast"); spinnerVisible = false; } }; </script>
我查了几个相关问题但没找到合适的解决方案,现在希望能得到有效的修复方法。
解决方案:利用Bootstrap内置布局类实现自适应居中+单行文本
其实不用写这么复杂的自定义CSS,Bootstrap已经提供了现成的flex布局类,能完美解决居中、自适应和单行文本的问题,同时兼容响应式:
修改后的HTML
<!-- 用Bootstrap的flex类实现全屏居中,垂直排列图标和文本 --> <div class="position-fixed top-0 start-0 w-100 h-100 d-flex flex-column align-items-center justify-content-center" id="spinner" style="z-index: 9999;"> <i class="fa fa-cog fa-spin" style="font-size: 40px;"></i> <!-- text-nowrap 保证单行,text-center 居中,mt-2 给图标和文本加间距 --> <span class="spinner-text text-nowrap text-center mt-2" style="font-size: 20px;">Please wait while we gather data from wherever...</span> </div>
修改后的CSS(只保留必要的自定义样式)
.spinner-text { /* 可选:如果文本过长,超出视口时显示省略号 */ max-width: 90vw; overflow: hidden; text-overflow: ellipsis; }
JavaScript 保持原有代码即可
为什么这样修改?
- Bootstrap flex布局类:
d-flex flex-column让图标和文本垂直排列,align-items-center保证水平居中,justify-content-center实现垂直居中,天然支持响应式,窗口变化时自动适配。 - 单行文本处理:
text-nowrap强制文本不换行,加上max-width: 90vw和省略号样式,避免文本过长撑破布局。 - 定位与层级:
position-fixed top-0 start-0 w-100 h-100让容器占满整个视口,z-index: 9999确保 spinner 在其他内容上方显示(原来的z-index: -1会让它被其他元素盖住,这也是个隐藏小问题)。
这样修改后,文本既能保持单行,又能和图标完美居中对齐,窗口尺寸变化时也能自适应,完全兼容Bootstrap的响应式特性。
内容的提问来源于stack exchange,提问作者coolhand
相关产品推荐
相关产品推荐

