emerico
5/20/2016 - 7:15 AM

Center bootstrap modal, Vertically and Horizontally

Center bootstrap modal, Vertically and Horizontally

(function ($) {
    "use strict";
    function $fixBootstrapModalPosition() {
        $(this).css('display', 'block');
        var $dialog  = $(this).find(".modal-dialog"),
            offset       = ($(window).height() - $dialog.height()) / 2,
            bottomMargin = parseInt($dialog.css('marginBottom'), 10);

        // Make sure you don't hide the top part of the modal w/ a negative margin if it's longer than the screen height, and keep the margin equal to the bottom margin of the modal
        if(offset < bottomMargin) offset = bottomMargin;
        $dialog.css("margin-top", offset);
    }

    $(document).on('show.bs.modal', '.modal', $fixBootstrapModalPosition);
    $(window).on("resize", function () {
        $('.modal:visible').each($fixBootstrapModalPosition);

    });
})(jQuery);

// Alternate:- You can add this css if you don't want to use js
/*
.modal {
    position: fixed;
    top: 50% !important;
    left: 50%;
    transform: translate(-50%, -50%);
}
*/