Skip to content

Instantly share code, notes, and snippets.

@claviska
Last active May 15, 2020 06:29
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save claviska/ab56d08bb19d011e3c35 to your computer and use it in GitHub Desktop.
Save claviska/ab56d08bb19d011e3c35 to your computer and use it in GitHub Desktop.
Vertically Centered Bootstrap Modals
/**
* Vertically center Bootstrap 3 modals so they aren't always stuck at the top
*/
$(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);
});
});
@Graahf
Copy link

Graahf commented Apr 14, 2016

If you use loaded instead of show, you can center ajax based modals, where content are loaded on click.

$('.modal').on('loaded.bs.modal', reposition);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment