Vertically center bootstrap modals without setting a height
. Modal max-height will not exceed the window height with scrollable .modal-body and adapts on resize.
You will need these JS and CSS snippets:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
function adjustModalMaxHeightAndPosition(){ $('.modal').each(function(){ if($(this).hasClass('in') === false){ $(this).show(); } var contentHeight = $(window).height() - 60; var headerHeight = $(this).find('.modal-header').outerHeight() || 2; var footerHeight = $(this).find('.modal-footer').outerHeight() || 2; $(this).find('.modal-dialog').addClass('modal-dialog-center').css({ 'margin-top': function () { var mH = $(this).outerHeight(); var wH = $(window).height(); return (mH < wH ) ? -( mH * 0.6): -( wH * 0.5) + 12; }, 'margin-left': function () { return -($(this).outerWidth() / 2); } }); if($(this).hasClass('in') === false){ $(this).hide(); } }); } if ($(window).height() >= 320){ $(window).resize(adjustModalMaxHeightAndPosition).trigger("resize"); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
.modal-dialog-center { margin: 0; margin-bottom: 12px; position: absolute; top: 50%; left: 50%; } .modal-footer { margin-top: 0; } @media (max-width: 767px) { .modal-dialog-center { width: 100%; } } |