Vertically centering Bootstrap modal window

前端 未结 30 1898
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  醉梦人生
    2020-12-07 07:50

    Because gpcola's answer didn't work for me, I edited a bit so its works now. I used "margin-top" instead of transform. Also, i use the "show" instead of "shown" event because after it gave me a very bad jump of positioning (visible when you have bootstrap animations on). Be sure to set the display to "block" before positioning, otherwise $dialog.height() will be 0 and the modal will not be centered completely.

    (function ($) {
        "use strict";
        function centerModal() {
            $(this).css('display', 'block');
            var $dialog  = $(this).find(".modal-dialog"),
            offset       = ($(window).height() - $dialog.height()) / 2,
            bottomMargin = parseInt($dialog.css('marginBottom'), 10);
    
            // 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
            if(offset < bottomMargin) offset = bottomMargin;
            $dialog.css("margin-top", offset);
        }
    
        $(document).on('show.bs.modal', '.modal', centerModal);
        $(window).on("resize", function () {
            $('.modal:visible').each(centerModal);
        });
    }(jQuery));
    

提交回复
热议问题