欢迎光临
我们一直在努力

怎么将Bootstrap模态垂直居中对齐

小编给大家分享一下怎么将Bootstrap模态垂直居中对齐,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

答案:使用CSSmargin-top属性

默认情况下,Bootstrap模态窗口与页面顶部对齐,并留有一些空白。但是您可以使用一个简单的JavaScript技巧将其垂直对齐在页面中间,如下面的示例所述。此解决方案将动态调整模式的对齐方式,即使用户调整浏览器窗口的大小,也始终将其保持在页面中央。

例试试这个代码»

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Vertical Center Alignment of Bootstrap Modal Dialog</title>

<link rel="stylesheet" href="css/bootstrap.min.css">

<script src="js/jquery-3.5.1.min.js"></script>

<script src="js/bootstrap.min.js"></script>

<script>

$(document).ready(function(){

    function alignModal(){

        var modalDialog = $(this).find(".modal-dialog");

        // Applying the top margin on modal to align it vertically center

        modalDialog.css("margin-top", Math.max(0, ($(window).height() – modalDialog.height()) / 2));

    }

    // Align modal when it is displayed

    $(".modal").on("shown.bs.modal", alignModal);

    // Align modal when user resize the window

    $(window).on("resize", function(){

        $(".modal:visible").each(alignModal);

    });   

});

</script>

</head>

<body>

<div class="m-4">

    <!– Button HTML (to Trigger Modal) –>

    <a href="#myModal" class="btn btn-primary btn-lg" data-toggle="modal">Launch Demo Modal</a>

    <!– Modal HTML –>

    <div id="myModal" class="modal">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <h6 class="modal-title">Confirmation</h6>

                    <button type="button" class="close" data-dismiss="modal">&times;</button> 

                </div>

                <div class="modal-body">

                    <p>Do you want to save changes you made to document before closing?</p>

                    <p class="text-warning"><small>If you don't save, your changes will be lost.</small></p>

                </div>

                <div class="modal-footer">

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

                    <button type="button" class="btn btn-primary">Save changes</button>

                </div>

            </div>

        </div>

    </div>

</div>     

</body>

</html>

以上是“怎么将Bootstrap模态垂直居中对齐”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注云搜网行业资讯频道!

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。