首页 文章

垂直居中的Bootstrap模态窗口

提问于
浏览
172

我想将我的模态集中在视口(中间)我试图添加一些css属性

.modal { position: fixed; top:50%; left:50%; }

我正在使用这个例子http://jsfiddle.net/rniemeyer/Wjjnd/

我试过了

$("#MyModal").modal('show').css(
    {
        'margin-top': function () {
            return -($(this).height() / 2);
        },
        'margin-left': function () {
            return -($(this).width() / 2);
        }
    })

30 回答

  • 1

    我的选择,只是一点点CSS :(不在IE8中工作)

    .modal.fade .modal-dialog {
        transform: translate(-50%, -80%);
    }
    
    .modal.in .modal-dialog {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        margin-top: 0px;
    }
    

    您可以使用第一个规则来更改模态的显示方式 .

    使用:Bootstrap 3.3.4

  • 18

    只需将以下CSS添加到现有的CSS中,它对我来说很好

    .modal {
      text-align: center;
    }
    @media screen and (min-width: 768px) {
        .modal:before {
          display: inline-block;
          vertical-align: middle;
          content: " ";
          height: 100%;
        }
    }
    .modal-dialog {
      display: inline-block;
      text-align: left;
      vertical-align: middle;
    }
    
  • 1

    不需要我们的javascript . Boostrap模态在出现时会添加.in类 . 只需使用flex css修改modalclassName.fade.in的这个类组合就可以了 .

    添加此css可垂直和水平居中显示模态 .

    .modal.fade.in {
        display: flex !important;
        justify-content: center;
        align-items: center;
    }
    .modal.fade.in .modal-dialog {
        width: 100%;
    }
    
  • 5

    这样做的工作:http://jsfiddle.net/sRmLV/1140/

    它使用helper-div和一些自定义css . 不需要javascript或jQuery .

    HTML (基于Bootstrap的demo-code

    <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>
    
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="vertical-alignment-helper">
            <div class="modal-dialog vertical-align-center">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
    
                        </button>
                         <h4 class="modal-title" id="myModalLabel">Modal title</h4>
    
                    </div>
                    <div class="modal-body">...</div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Save changes</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    

    CSS

    .vertical-alignment-helper {
        display:table;
        height: 100%;
        width: 100%;
        pointer-events:none; /* This makes sure that we can still click outside of the modal to close it */
    }
    .vertical-align-center {
        /* To center vertically */
        display: table-cell;
        vertical-align: middle;
        pointer-events:none;
    }
    .modal-content {
        /* Bootstrap sets the size of the modal in the modal-dialog class, we need to inherit it */
        width:inherit;
        max-width:inherit; /* For Bootstrap 4 - to avoid the modal window stretching full width */
        height:inherit;
        /* To center horizontally */
        margin: 0 auto;
        pointer-events: all;
    }
    
  • 2

    因为gpcola的答案对我来说不起作用,所以我编辑了一下它的作品 . 我使用“margin-top”而不是transform . 此外,我使用“显示”而不是“显示”事件,因为它给我一个非常糟糕的定位跳跃(当你有自举动画时可见) . 确保在定位之前将显示设置为“阻止”,否则$ dialog.height()将为0并且模态将不会完全居中 .

    (function ($) {
        "use strict";
        function centerModal() {
            $(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', centerModal);
        $(window).on("resize", function () {
            $('.modal:visible').each(centerModal);
        });
    }(jQuery));
    
  • 0

    这就是我为我的应用所做的 . 如果你看看bootstrap.css文件中的以下类.modal-dialog的默认填充为10px和@media屏幕,并且(min-width:768px).modal-dialog的顶部填充设置为30px . 因此,在我的自定义css文件中,我将所有屏幕的顶部填充设置为15%,而未指定媒体屏幕宽度 . 希望这可以帮助 .

    .modal-dialog {
      padding-top: 15%;
    }
    
  • 70

    我发现所有HTML5浏览器的最佳方式:

    body.modal-open .modal {
        display: flex !important;
        height: 100%;
    } 
    
    body.modal-open .modal .modal-dialog {
        margin: auto;
    }
    
  • 2
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="table">
            <div class="table-cell">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                        </div>
                        <div class="modal-body">
                            ...
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-primary">Save changes</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    

    //样式

    .table {
     display: table;
     height:100%;
    }
    .table-cell {
    display: table-cell;
    vertical-align: middle;
    }
    
  • 93

    在.modal.fade.in中重写top参数以强制在自定义声明中设置的值,在顶部后面添加 !important 关键字 . 这会强制浏览器使用该值并忽略关键字的任何其他值 . 这样做的缺点是你无法在其他地方覆盖这个值 .

    .modal {
        position: fixed;
        top: 50% !important;
        left: 50%;
    }
    
  • 0

    这完美适合我:

    .modal {
    text-align: center;
    padding: 0!important;
    }
    
    .modal:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
    margin-right: -4px;
    }
    
    .modal-dialog {
    display: inline-block;
    text-align: left;
    vertical-align: middle;
    }
    

    完成 Demo 网址:https://codepen.io/dimbslmh/full/mKfCc

  • 2

    因为这里的大部分答案都不起作用,或者只是部分起作用:

    body.modal-open .modal[style]:not([style='display: none;']) {
        display: flex !important;
        height: 100%;
    } 
    
    body.modal-open .modal[style]:not([style='display: none;']) .modal-dialog {
        margin: auto;
    }
    

    您必须使用[样式]选择器仅将样式应用于当前活动的模态而不是所有模态 . .in 会很棒,但它似乎只是在转换完成后添加,这太晚了,并且会导致一些非常糟糕的转换 . 幸运的是,似乎bootstrap总是在模态上应用一个样式属性,就像它开始显示所以这有点hacky,但它的工作原理 .

    :not([style='display: none;']) 部分是一种解决方法,用于引导程序无法正确删除样式属性,而是在关闭对话框时将样式显示设置为无 .

  • 240

    您可以在Bootstrap 3模式上实现垂直对齐中心,如下所示:

    .modal-vertical-centered {
      transform: translate(0, 50%) !important;
      -ms-transform: translate(0, 50%) !important; /* IE 9 */
      -webkit-transform: translate(0, 50%) !important; /* Safari and Chrome */
    }
    

    并将此css类添加到“模态对话框”容器中

    <div class="modal-dialog modal-vertical-centered">
    ...
    

    jsFiddle工作示例:http://jsfiddle.net/U4NRx/

  • 8

    最简洁,最简单的方法是使用Flexbox!以下内容将垂直对齐屏幕中央的Bootstrap 3模式,并且比此处发布的所有其他解决方案更清晰,更简单:

    body.modal-open .modal.in {
      display: flex !important;
      align-items: center;
    }
    

    注意:虽然这是最简单的解决方案,但由于浏览器的支持,它可能不适合所有人:http://caniuse.com/#feat=flexbox

    看起来(通常)IE落后了 . 就我而言,我为自己或客户开发的所有产品都是IE10 . (当支持旧版本的IE可以用于实际开发产品并更快地获得MVP时,投入开发时间来支持旧版IE是没有意义的 . 这当然不是每个人都有的奢侈品 .

    我已经看到较大的站点检测是否支持flexbox并将类应用于页面主体 - 但前端工程的这一级别非常强大,您仍然需要回退 .

    我鼓励人们接受网络的未来 . Flexbox很棒,如果可以,你应该开始使用它 .

    附: - 这个网站真的帮助我把Flexbox整体用于任何用例:http://flexboxfroggy.com/

    编辑:如果在一个页面上有两个模态,这应该适用于.modal.in

  • 6

    您可以使用:

    .modal {
        position: fixed;
        top: 50% !important;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    

    使其垂直和水平居中 .

  • 2

    从Bootstrap 4开始,添加了以下类,无需JavaScript即可实现此目的 .

    modal-dialog-centered
    

    你可以找到他们的文件here .

  • -5

    Advantages:

    即使比设备高,也可以访问

    • 模态内容

    • 不使用 display:table-cell (这不适用于布局)

    • 不需要对默认的Bootstrap 3模态进行任何修改 markup

    • 定位是纯CSS . 添加JS是为了在点击/点击下方和上方关闭模式

    • 我为那些使用 gulpgrunt 的人包含了未加前缀的 SCSS

    // closes the modal on click/tap below/above the modal
    
    $('.modal-dialog').on('click tap', function(e){
        if (e.target.classList.contains('modal-dialog')) {
        $('.modal').modal('hide');
      }
    })
    
    .modal-dialog {
      display: -webkit-box;
      display: -webkit-flex;
      display: -moz-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-orient: vertical;
      -webkit-box-direction: normal;
      -webkit-flex-direction: column;
         -moz-box-orient: vertical;
         -moz-box-direction: normal;
          -ms-flex-direction: column;
              flex-direction: column;
      -webkit-box-pack: center;
      -webkit-justify-content: center;
         -moz-box-pack: center;
          -ms-flex-pack: center;
              justify-content: center;
      overflow-y: auto;
      min-height: -webkit-calc(100vh - 60px);
      min-height: -moz-calc(100vh - 60px);
      min-height: calc(100vh - 60px);
    }
    @media (max-width: 767px) {
      .modal-dialog {
        min-height: -webkit-calc(100vh - 20px);
        min-height: -moz-calc(100vh - 20px);
        min-height: calc(100vh - 20px);
      }
    }
    
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
    
    <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
      Launch demo modal
    </button>
    
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
          </div>
          <div class="modal-body">
            
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>
    

    Note :我打算用最新的Bootstrap 3规范来更新这个答案 . 对于Bootstrap 4解决方案,请参阅this answer(现在它们或多或少相同,但是它们可能会分时) . 如果您发现任何错误或问题,请告诉我,我会更新 . 谢谢 .


    清洁,无前缀 SCSS (用于 gulp / grunt ):

    .modal-dialog {
      display: flex;
      flex-direction: column;
      justify-content: center;
      overflow-y: auto;
      min-height: calc(100vh - 60px);
      @media (max-width: 767px) {
        min-height: calc(100vh - 20px);
      }
    }
    
  • 7

    又一个CSS解 . 对于大于视口的弹出窗口不起作用 .

    .modal-dialog {
        position: absolute;
        right: 0;
        left: 0;
        margin-top: 0;
        margin-bottom: 0; 
    }
    .modal.fade .modal-dialog {
        transition: top 0.4s ease-out;
        transform: translate(0, -50%);
        top: 0;
    }
    .modal.in .modal-dialog {
        transform: translate(0, -50%);
        top: 50%;
    }
    

    .modal-dialog 类中将位置重写为绝对(从相对位置)并使内容居中 right:0, left: 0

    .modal.fade .modal-dialog , .modal.in .modal-dialog 中设置过渡动画超过 top 而不是翻译 .

    如果弹出窗口较小, margin-top 会将弹出窗口略微移动到中心以下,如果弹出窗口较长,则模式会被标头卡住 . 因此 margin-top:0, margin-bottom:0

    需要进一步完善它 .

  • 3

    对于那些使用angular-ui bootstrap的人,可以根据以上信息添加以下类:

    注意:不需要进行其他更改,它将解决所有模态 .

    // The 3 below classes have been placed to make the modal vertically centered
    .modal-open .modal{
        display:table !important;
        height: 100%;
        width: 100%;
        pointer-events:none; /* This makes sure that we can still click outside of the modal to close it */
    }
    
    .modal-dialog{
        display: table-cell;
        vertical-align: middle;
        pointer-events: none;
    }
    
    .modal-content {
        /* Bootstrap sets the size of the modal in the modal-dialog class, we need to inherit it */
        width:inherit;
        height:inherit;
        /* To center horizontally */
        margin: 0 auto;
        pointer-events: all;
    }
    
  • 3

    基于Arany's answer,还可以占页面滚动 .

    (function($) {
        "use strict";
        function positionModals(e) {
            var $this = $(this).css('display', 'block'),
                $window = $(window),
                $dialog = $this.find('.modal-dialog'),
                offset = ($window.height() - $window.scrollTop() - $dialog.height()) / 2,
                marginBottom = parseInt($dialog.css('margin-bottom'), 10);
    
            $dialog.css('margin-top', offset < marginBottom ? marginBottom : offset);
        }
    
        $(document).on('show.bs.modal', '.modal', positionModals);
    
        $(window).on('resize', function(e) {
            $('.modal:visible').each(positionModals);
        });
    }(jQuery));
    
  • 8

    我认为这是一个比Rens de Nobel解决方案更简洁的纯CSS解决方案 . 此外,这不会阻止通过单击对话框关闭对话框 .

    http://plnkr.co/edit/JCGVZQ?p=preview

    只需使用.modal-dialog类将一些CSS类添加到DIV容器中,以获得比bootstraps CSS更高的特异性,例如: .centered .

    HTML

    <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
      <div class="modal-dialog centered modal-lg">
        <div class="modal-content">
          ...
        </div>
      </div>
    </div>
    

    并使这个.modal-dialog.centered容器固定并正确定位 .

    CSS

    .modal .modal-dialog.centered {
        position: fixed;
        bottom: 50%;
        right: 50%;
        transform: translate(50%, 50%);
    }
    

    或者甚至更简单地使用flexbox .

    CSS

    .modal {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
  • 56

    这适用于BS3,未在v2中测试 . 它将模态垂直居中 . 请注意,它会在那里转换 - 如果你想要它只是出现在位置编辑 transition 属性 .modal-dialog

    centerModal = function() {
        var $dialog = $(this).find(".modal-dialog"),
            offset = ($(window).height() - $dialog.height()) / 2;
    
        // Center modal vertically in window
        $dialog.css({
            'transform': 'translateY(' + offset + 'px) !important',
        });
    };
    
    $('.modal').on('shown.bs.modal', centerModal);
    $(window).on("resize", function() {
        $('.modal').each(centerModal);
    });
    
  • 3
    e(document).on('show.bs.modal', function () {
            if($winWidth < $(window).width()){
                $('body.modal-open,.navbar-fixed-top,.navbar-fixed-bottom').css('marginRight',$(window).width()-$winWidth)
            }
        });
        e(document).on('hidden.bs.modal', function () {
            $('body,.navbar-fixed-top,.navbar-fixed-bottom').css('marginRight',0)
        });
    
  • 10

    如果模态高于屏幕的高度,这需要Arany的答案并使其工作:

    function centerModal() {
        $(this).css('display', 'block');
        var $dialog = $(this).find(".modal-dialog");
        var offset = ($(window).height() - $dialog.height()) / 2;
        //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
        var bottomMargin = $dialog.css('marginBottom');
        bottomMargin = parseInt(bottomMargin);
        if(offset < bottomMargin) offset = bottomMargin;
        $dialog.css("margin-top", offset);
    }
    
    $('.modal').on('show.bs.modal', centerModal);
    $(window).on("resize", function () {
        $('.modal:visible').each(centerModal);
    });
    
  • 1

    使模态真正对齐中间所有对话框 .

    /* 注意:

    1.即使您不需要指定选择器,它也会从文档中找到所有模态并使其垂直居中

    2.为了避免中间某些特定模态为中心,你可以使用:不是选择器在点击事件中

    • /
    $( "[data-toggle='modal']" ).click(function(){
         var d_tar = $(this).attr('data-target'); 
         $(d_tar).show();   
         var modal_he = $(d_tar).find('.modal-dialog .modal-content').height(); 
         var win_height = $(window).height();
         var marr = win_height - modal_he;
         $('.modal-dialog').css('margin-top',marr/2);
      });
    

    来自米兰潘迪亚

  • 1

    要添加垂直模态居中到bootstrap modal.js,我在 Modal.prototype.show 函数的末尾添加了这个:

    var $modalDialog = $('.modal-dialog'),
            modalHeight = $modalDialog.height(),
            browserHeight = window.innerHeight;
    
        $modalDialog.css({'margin-top' : modalHeight >= browserHeight ? 0 : (browserHeight - modalHeight)/2});
    
  • 1
    .modal.in .modal-dialog {
        position: relative;
        top: 50%;
        transform: translateY(-50%);
    }
    
  • 13

    使用这个以模态为中心的简单脚本 .

    如果需要,可以设置自定义类(例如:.modal.modal-vcenter而不是.modal),仅将功能限制为某些模态 .

    var modalVerticalCenterClass = ".modal";
    
    function centerModals($element) {
        var $modals;
        if ($element.length) {
          $modals = $element;
        } else {
        $modals = $(modalVerticalCenterClass + ':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);
    });
    }
    $(modalVerticalCenterClass).on('show.bs.modal', function(e) {
        centerModals($(this));
    });
    $(window).on('resize', centerModals);
    

    同时为模态的水平间距添加此CSS修复;我们在模态上显示滚动,主体滚动由Bootstrap自动隐藏:

    /* scroll fixes */
    .modal-open .modal {
      padding-left: 0px !important;
      padding-right: 0px !important;
      overflow-y: scroll;
    }
    
  • 0

    这个问题的另一个CSS答案......
    此解决方案仅使用CSS来实现所需的效果,同时仍然保持通过单击其外部来关闭模态的能力 . 它还允许您设置 .modal-content 高度和宽度最大值,以便弹出窗口不会超出视口 . 当内容超出模态大小时,将自动显示滚动 .

    note:
    应该省略Bootstrap建议 .modal-dialog div ,以使其正常工作(似乎没有破坏任何东西) . 在Chrome 51和IE 11中测试过 .

    CSS Code:

    .modal {
       height: 100%;
       width: 100%;
    }
    
    .modal-content {
       margin: 0 auto;
       max-height: 600px;
       max-width: 50%;
       overflow: auto;
       transform: translateY(-50%);
    }
    

    EDIT: .modal-dialog 类允许您选择用户是否可以通过单击模态本身的外部来关闭模态 . 大多数模态都有一个明确的'close'或'cancel'按钮 . 使用此变通办法时请记住这一点 .

  • 9

    使用宽度和高度集中模态的最佳解决方案是,在css add和in modal中将这个'centralize'添加为类 .

    .centralize{
       position:absolute;
       left:50%;
       top:50%;
    
       background-color:#fff;
       transform: translate(-50%, -50%);
       width: 40%; //specify watever u want
       height: 50%;
       }
    
  • 1

    4小时后,我找到了解决方案 . 以不同分辨率(台式机,平板电脑,智能手机)为中心模式:

    index.php

    <! - Bootstrap core CSS ->
         <link href=".../css/bootstrap-modal-bs3patch.css" rel="stylesheet">
         <link href=".../css/bootstrap-modal.css" rel="stylesheet">
    

    文件 bootstrap-modal-bs3patch.css 我从https://github.com/jschr/bootstrap-modal下载了它

    然后我修改了这个文件 . Css如下:

    body.modal-open,
    . modal-open. navbar-fixed-top,
    . modal-open. navbar-fixed-bottom {
       margin-right: 0;
    }
    
    
    . {modal
       padding: 0;
    }
    
    . modal.container {
       max-width: none;
    }
    
    @ media (min-width: 768px) and (max-width: 992px) {
    
    . {modal-dialog
    background-color: black;
    position: fixed;
    top: 20%! important;
    left: 15%! important;
    }
    }
    
    @ media (min-width: 992px) and (max-width: 1300px) {
    
    . {modal-dialog
    background-color: red;
    position: fixed;
    top: 20%! important;
    left: 20%! important;
    }
    }
    
    @ media (min-width: 1300px) {
    
    . {modal-dialog
    background-color: # 6e7ec3;
    position: fixed;
    top: 40%! important;
    left: 35%! important;
    }
    }
    

    我做了不同分辨率的测试和 it works

相关问题