LoginSignup
2
3

More than 5 years have passed since last update.

modalの上下センタリング

Posted at

Bootstrapなどで利用するモーダルの上下センタリングを行う。
クローンを作成してmodalの高さを計算し,marginで調整する。

(function($) {
    $(function() {
        function centerModals($element) {
            var $modals;
            if ($element.length) {
                $modals = $element;
            } else {
                $modals = $(".modal" + ':visible');
            }
            $modals.each( function(i) {
                var $clone = $(this).clone().css('display', 'block').appendTo('body');
                var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2);
                top = top > 0 ? top : 0;
                $clone.remove();
                $(this).find('.modal-content').css("margin-top", top);
            });
        }

        // modal表示時
        $(".modal").on('show.bs.modal', function(e) {
            centerModals($(this));
        });
        // windowリサイズ時
        $(window).on('resize', centerModals);
    });
})(jQuery);
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3