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

如何在Bootstrap 4中实现文本垂直居中?

解决Bootstrap模态框头部图标与标题的垂直对齐问题

嘿,刚学Bootstrap遇到这种布局小问题太正常啦!我来帮你搞定模态框头部里图标和标题的垂直对齐~

核心思路

Bootstrap 4及以上版本本身基于Flexbox,所以我们可以直接用框架自带的工具类来实现对齐,不用额外写复杂的CSS。如果是Bootstrap 3,也有简单的行内样式方案。


方案1:Bootstrap 4/5 推荐用法(Flex工具类)

直接给modal-header添加flex相关的工具类,让内部元素自动垂直居中:

<div id="actionConfirmation" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="actionModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <!-- 修改后的模态框头部 -->
      <div class="modal-header d-flex align-items-center">
        <!-- 这里放你的图标,比如用Bootstrap Icons -->
        <i class="bi bi-exclamation-triangle me-3" style="font-size: 1.5rem;"></i>
        <!-- 模态框标题 -->
        <h5 class="modal-title" id="actionModalLabel">确认执行此操作?</h5>
        <!-- 关闭按钮自动靠右 -->
        <button type="button" class="btn-close ms-auto" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div id="partialViewContent">
        <!-- 你的局部视图内容 -->
      </div>
    </div>
  </div>
</div>

每个工具类的作用:

  • d-flex:将modal-header转为Flex容器,开启Flex布局
  • align-items-center:让容器内的所有元素垂直方向居中对齐
  • me-3:给图标右侧添加间距(Bootstrap 4用mr-3),和标题区分开
  • ms-auto:让关闭按钮自动推到容器最右侧,保持布局美观

方案2:Bootstrap 3 兼容方案

如果还在使用Bootstrap 3(非Flex布局),可以通过vertical-align属性实现对齐:

<div id="actionConfirmation" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="actionModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <span class="glyphicon glyphicon-warning-sign" style="font-size: 1.5rem; vertical-align: middle; margin-right: 10px;"></span>
        <h4 class="modal-title" id="actionModalLabel" style="display: inline-block; vertical-align: middle;">确认执行此操作?</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div id="partialViewContent">
        <!-- 你的局部视图内容 -->
      </div>
    </div>
  </div>
</div>

关键要点:

  • 把标题设置为display: inline-block,让它和图标在同一行
  • 给图标和标题都加上vertical-align: middle,实现垂直居中

小提示

  • 不管用哪种图标(Bootstrap自带、Font Awesome或自定义图标),只要确保图标是inline或inline-block元素,都能适配上面的方法
  • 尽量优先使用Bootstrap自带的工具类,减少自定义CSS的编写,这样更符合框架规范,也便于后续维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:17:55