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

如何在Bootstrap 5.3中将模态框头部拆分为两行并居中文本?

解决Bootstrap 5.3模态框Header内元素换行并居中的问题

问题原因

Bootstrap的.modal-header默认是flex横向布局,所以里面的<h1>和<p>会被自动排列成一行——哪怕你给元素加了d-block也没用,因为flex容器下子元素的块级属性会被flex布局特性覆盖。

解决方案(两种可选)

方案1:修改模态框Header的flex方向

直接给.modal-header添加flex-column(改为垂直flex布局)和align-items-center(垂直布局下让子元素水平居中),再给<h1>和<p>加text-center实现文本居中:

<div class="modal fade" id="product-review-modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header flex-column align-items-center">
                <h1 class="modal-title fs-5 text-center" id="exampleModalLabel">Review of "Product Name"</h1>
                <p class="text-center mb-0">Please review this product! Thank you for your cooperation!</p>
            </div>
            <div class="modal-body">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

注:给<p>加mb-0是去掉默认下边距,避免Header内部间距过大,可根据需求调整。

方案2:用容器包裹Header内的文本元素

把<h1>和<p>放进一个<div>容器里,给容器加text-center实现文本居中,再给.modal-header加justify-content-center让整个容器水平居中:

<div class="modal fade" id="product-review-modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header justify-content-center">
                <div class="text-center">
                    <h1 class="modal-title fs-5" id="exampleModalLabel">Review of "Product Name"</h1>
                    <p class="mb-0">Please review this product! Thank you for your cooperation!</p>
                </div>
            </div>
            <div class="modal-body">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

两种方法都能实现<h1>和<p>各占一行、文本居中的效果,可根据后续是否需要在Header添加其他元素来选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 04:51:05