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('', 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.

Simple, Beautiful Publishing

This website is powered by Postleaf, an open source blogging platform I built myself. Check it out if you’re looking for a fresh, modern approach to content management.

Author avatar

About the author

Cory LaViska is a founder, web developer, and bootstrapper based in Orlando, Florida. Need to get in touch? You can connect with him on Twitter. Looking for a simple, no-worry CMS for your clients? Try my Surreal CMS!