垂直居中的Bootstrap模态窗口

use*_*813 177 javascript twitter-bootstrap bootstrap-modal

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

 .modal { position: fixed; top:50%; left:50%; }   
Run Code Online (Sandbox Code Playgroud)

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

我试过了

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

RNo*_*bel 250

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

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

HTML(基于Bootstrap的演示代码)

<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>
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 不知道这是否已经更新,因为用户的评论说它不起作用,点击内部模态元素,但这是100%适用于我现在,使用上面的小提琴中的示例.非常感谢您的帮助和上述所有评论. (4认同)
  • @pcatre,谢谢你的提示!我已经更新了代码并修复了这个问题.设置指针事件:无; 在对齐类上做了诀窍.在IE11,最新Chrome和Firefox以及iOS Safari中测试过. (3认同)
  • 从引导程序4开始,增加了以模态对话框为中心的功能,不再需要此功能。请在下面查看该答案。 (2认同)

Ara*_*any 93

因为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));
Run Code Online (Sandbox Code Playgroud)

  • 这个很完美!只是代替$(document).height(),它在第4行使用$(window).height()是正确的.另外我会将最后一行更改为:`$('.modal:visible').each(centerModal) );` (6认同)

小智 77

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

.modal-dialog {
  padding-top: 15%;
}
Run Code Online (Sandbox Code Playgroud)

  • 这只适用于小型的alret盒子,不适用于大型盒子 (6认同)

tah*_*hid 59

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

body.modal-open .modal {
    display: flex !important;
    height: 100%;
} 

body.modal-open .modal .modal-dialog {
    margin: auto;
}
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个解决方案,很干净.不确定桌面版或旧版本的Safari,但它似乎在iOS 8上没问题. (2认同)
  • 这是一个伟大的css只有渐进增强.不需要js,任何不支持flexbox的浏览器都将获得默认的bootstrap模式放置. (2认同)

小智 19

<!-- 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>
Run Code Online (Sandbox Code Playgroud)

//样式

.table {
 display: table;
 height:100%;
}
.table-cell {
display: table-cell;
vertical-align: middle;
}
Run Code Online (Sandbox Code Playgroud)

  • 这是普遍的答案.我不知道为什么没有人投票赞成. (3认同)
  • 我经历了至少4个SO条目,每个条目都有十几个提案.顺便说一句,在HTML5时代,至少应该在一些框架的功能上构建它.而不是杂耍. (3认同)
  • 迄今为止最好的答案。这会创建一个滚动条,但您可以通过使 .modal-open .modal { overflow-y: hidden; 禁用它。} (2认同)

Ale*_*ijk 14

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

.modal {
    position: fixed;
    top: 50% !important;
    left: 50%;
}
Run Code Online (Sandbox Code Playgroud)

  • 位置:固定为我做了诀窍!谢谢! (2认同)

Ami*_*ian 12

这完美适合我:

.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;
}
Run Code Online (Sandbox Code Playgroud)

完整的演示 URL:https://codepen.io/dimbslmh/full/mKfCc


Ary*_*mon 10

您可以使用:

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

使其垂直和水平居中.

  • 这是使用CSS的真正“如何使某些内容居中”而不使用Flex。上下文是Bootstrap还是模态的事实应该是无关紧要的。所有其他答案都过于矫kill过正。 (2认同)

Rob*_*Kee 10

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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


jca*_*uso 9

从Bootstrap 4开始,添加了以下类,以便在没有JavaScript的情况下为您实现此目的.

modal-dialog-centered
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到他们的文档.

  • 这是引导程序 4 的最佳答案。 (3认同)
  • @vd 这是理解的,因为文档说“将 .modal-dialog-centered 添加到 .modal-dialog 以垂直居中模式。” 我将更新我的答案,以反映那些没有明白这一点的人。 (2认同)

EGu*_*lli 8

您可以在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 */
}
Run Code Online (Sandbox Code Playgroud)

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

<div class="modal-dialog modal-vertical-centered">
...
Run Code Online (Sandbox Code Playgroud)

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

  • 我的模态就在这个页面上 (3认同)
  • 是的!我使用: .modal.fade.in { top: 50%; 变换:翻译Y(-50%);} (2认同)

Gre*_*ass 8

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

body.modal-open .modal.in {
  display: flex !important;
  align-items: center;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

PS - 这个网站真的帮助我把握整个Flexbox并将其应用于任何用例:http://flexboxfroggy.com/

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


And*_*hiu 7

好处:

  • 即使比设备高,也可以访问模态内容
  • 不使用display:table-cell(这不适用于布局)
  • 不需要对默认的Bootstrap 3模态进行任何修改 markup
  • 定位是纯CSS.添加JS是为了在点击/点击下方及其上方关闭模式
  • SCSS为那些使用gulp或者的人包含了无前缀grunt

// 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');
  }
})
Run Code Online (Sandbox Code Playgroud)
.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);
  }
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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


清洁,无前缀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);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 最佳解决方案IMO. (2认同)