Vertically centering Bootstrap modal window

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

    Based on Arany's answer, but also accounting for page scroll.

    (function($) {
        "use strict";
        function positionModals(e) {
            var $this = $(this).css('display', 'block'),
                $window = $(window),
                $dialog = $this.find('.modal-dialog'),
                offset = ($window.height() - $window.scrollTop() - $dialog.height()) / 2,
                marginBottom = parseInt($dialog.css('margin-bottom'), 10);
    
            $dialog.css('margin-top', offset < marginBottom ? marginBottom : offset);
        }
    
        $(document).on('show.bs.modal', '.modal', positionModals);
    
        $(window).on('resize', function(e) {
            $('.modal:visible').each(positionModals);
        });
    }(jQuery));
    

提交回复
热议问题