Vertically centering Bootstrap modal window

前端 未结 30 1944
被撕碎了的回忆
被撕碎了的回忆 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:49

    Use this simple script that centers the modals.

    If you want you can set a custom class (ex: .modal.modal-vcenter instead of .modal) to limit the functionality only to some modals.

    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);
    

    Also add this CSS fix for the modal's horizontal spacing; we show the scroll on the modals, the body scrolls is hidden automatically by Bootstrap:

    /* scroll fixes */
    .modal-open .modal {
      padding-left: 0px !important;
      padding-right: 0px !important;
      overflow-y: scroll;
    }
    

提交回复
热议问题