Vertically Centering Bootstrap 3 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('', reposition);

    // Reposition when the window is resized
    $(window).on('resize', function() {


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

Creator of Surreal CMS and other web things. Follow me for tweets about JavaScript, CSS, and web programming.