Vertically centering Bootstrap modal window

前端 未结 30 1939
被撕碎了的回忆
被撕碎了的回忆 2020-12-07 07:00

I would like to center my modal on the viewport (middle) I tried to add some css properties

 .modal { position: fixed; top:50%; left:50%; }   
30条回答
  •  Happy的楠姐
    2020-12-07 07:50

    This takes Arany's answer and makes it work if the modal is taller than the height of the screen:

    function centerModal() {
        $(this).css('display', 'block');
        var $dialog = $(this).find(".modal-dialog");
        var offset = ($(window).height() - $dialog.height()) / 2;
        //Make sure you don't hide the top part of the modal w/ a negative margin if it's longer than the screen height, and keep the margin equal to the bottom margin of the modal
        var bottomMargin = $dialog.css('marginBottom');
        bottomMargin = parseInt(bottomMargin);
        if(offset < bottomMargin) offset = bottomMargin;
        $dialog.css("margin-top", offset);
    }
    
    $('.modal').on('show.bs.modal', centerModal);
    $(window).on("resize", function () {
        $('.modal:visible').each(centerModal);
    });
    

提交回复
热议问题