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

Bootstrap 5模态框无法实现页面垂直居中的技术求助

解决Bootstrap模态框垂直居中问题

直接用Bootstrap内置的modal-dialog-centered类就能实现模态框垂直居中,不需要自定义CSS或者mt-5这类手动调margin的类。你之前已经注释了正确写法,替换掉当前的modal-dialog类即可:

修改后的完整代码

</button>
<!-- </button> -->
<div class="text-dark ">
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content ">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel">Log in</h1>
                <button type="button" class="btn-close bg-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-start">
                <form>
                    <div class="mb-3">
                        <label for="exampleInputEmail1" class="form-label">Name</label>
                        <input type="text" class="form-control  text-dark" id="exampleInputEmail1" aria-describedby="emailHelp" required>
                    </div>
                    <div class="mb-3">
                        <label for="exampleInputEmail1" class="form-label">Email</label>
                        <input type="email" class="form-control  text-dark" id="exampleInputEmail1" aria-describedby="emailHelp" required>
                        <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
                    </div>
                    <div class="mb-3">
                        <label for="exampleInputPassword1" class="form-label">Password</label>
                        <input type="password" class="form-control text-dark" id="exampleInputPassword1" required>
                    </div>
            </div>
            <div class="modal-footer ">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>
</div>
</div>

补充说明

  • modal-dialog-centered是Bootstrap专为模态框垂直居中设计的类,通过flex布局自动适配视口高度实现居中,比手动加align-items-center d-flex更稳定,不会和模态框默认样式冲突。
  • 你之前用的mt-5是固定margin值,没法适配不同屏幕高度,内置类能做到真正的自适应垂直居中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:42:49