This is a two part question:
How can you position the modal vertically in the center when you don\'t know the exact height of the modal?
Is
Expanding on @Finik's excellent answer, this fix is only applied to non-mobile devices. I tested in IE8, Chrome, and Firefox 22 - it works with very long or short content.
.modal {
text-align: center;
}
@media screen and (min-device-width: 768px) {
.modal:before {
display: inline-block;
vertical-align: middle;
content: " ";
height: 100%;
}
}
.modal-dialog {
display: inline-block;
text-align: left;
vertical-align: middle;
}
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;
}
Here's one other css only method that works pretty well and is based on this: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/
sass:
.modal {
height: 100%;
.modal-dialog {
top: 50% !important;
margin-top:0;
margin-bottom:0;
}
//keep proper transitions on fade in
&.fade .modal-dialog {
transform: translateY(-100%) !important;
}
&.in .modal-dialog {
transform: translateY(-50%) !important;
}
}
Found the perfect solution from here
$(function() {
function reposition() {
var modal = $(this),
dialog = modal.find('.modal-dialog');
modal.css('display', 'block');
// Dividing by two centers the modal exactly, but dividing by three
// or four works better for larger screens.
dialog.css("margin-top", Math.max(0, ($(window).height() - dialog.height()) / 2));
}
// Reposition when a modal is shown
$('.modal').on('show.bs.modal', reposition);
// Reposition when the window is resized
$(window).on('resize', function() {
$('.modal:visible').each(reposition);
});
});
Consider using the bootstrap-modal plugin found here - https://github.com/jschr/bootstrap-modal
The plugin will center all of your modals
Adding this simple css also works.
.modal-dialog {
height: 100vh !important;
display: flex;
}
.modal-content {
margin: auto !important;
height: fit-content !important;
}