Vertically Centering Bootstrap Modals

Ever wished you could vertically center your Bootstrap modals? Here's some code that will let you do just that.

The code is pretty simple to understand. There's a function to handle the repositioning and a couple event handlers that tell it when to run. Here you go:

/**
 * 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);
    });

});

This will keep your modals centered vertically even when the window is resized. I've posted it here and as a gist over on GitHub. Inspired by an answer on StackOverflow.

Author avatar

About the author

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.