Bootstrap 3 modal vertical position center

后端 未结 30 1240
天涯浪人
天涯浪人 2020-11-28 00:15

This is a two part question:

  1. How can you position the modal vertically in the center when you don\'t know the exact height of the modal?

  2. Is

30条回答
  •  生来不讨喜
    2020-11-28 00:46

    var modalVerticalCenterClass = ".modal";
    function centerModals($element) {
        var $modals;
        if ($element.length) {
            $modals = $element;
        } else {
            $modals = $(modalVerticalCenterClass + ':visible');
        }
        $modals.each( function(i) {
            var $clone = $(this).clone().css('display', 'block').appendTo('body');
            var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2);
            top = top > 0 ? top : 0;
            $clone.remove();
            $(this).find('.modal-content').css("margin-top", top);
        });
    }
    $(modalVerticalCenterClass).on('show.bs.modal', function(e) {
        centerModals($(this));
    });
    $(window).on('resize', centerModals);
    

提交回复
热议问题