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.

Thanks for Reading

If you found this post helpful, please check out my service Surreal CMS. It’s a hosted content management system with beautiful inline editing and a ton of other great features!

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!