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

如何在Bootstrap 4模态框中水平居中标题?多种方法尝试无效

解决Bootstrap 4模态框标题水平居中的问题

嘿,我明白你为啥用text-center、mx-auto这些类没生效啦!Bootstrap 4的.modal-header是采用Flexbox布局的,默认的justify-content属性值是space-between——这个规则是用来让标题和右上角的关闭按钮分别左右对齐的,所以直接给标题加文本居中类,优先级会被Flex布局的规则覆盖,自然没效果。

下面给你两种实用的解决方案,按需选择:

方案1:让整个模态框头部内容居中(含关闭按钮)

如果不介意关闭按钮也跟着标题一起居中,直接给.modal-header添加Bootstrap的justify-content-center类就行,它会修改Flex容器的主轴对齐方式:

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header justify-content-center">
        <h5 class="modal-title" id="exampleModalLabel">居中的模态框标题</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        模态框内容示例
      </div>
    </div>
  </div>
</div>

方案2:仅让标题居中,保留关闭按钮在右上角

这是更常用的场景,给.modal-title添加mx-auto类即可。作为Flex子元素,mx-auto会让标题自动填充左右两侧的剩余空间,从而实现居中,同时不影响关闭按钮的位置:

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title mx-auto" id="exampleModalLabel">居中的模态框标题</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        模态框内容示例
      </div>
    </div>
  </div>
</div>

如果以上方法还是不行,检查一下有没有自定义CSS覆盖了Bootstrap的Flex规则,比如给.modal-header设置了display:block之类的,那得先把这个冲突去掉哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:41:53