如何使用CSS在Bootstrap V4模态框中垂直居中?

7

你能否用垂直对齐实用类包装一下它?http://v4-alpha.getbootstrap.com/utilities/vertical-align/ - Jorg
我尝试了 align-middle,但是没有起作用。 - wonderful world
2个回答

15
您可以通过覆盖 .modal-dialog 的位置来使模态框垂直居中,方法如下:
.modal.show .modal-dialog {
    -webkit-transform: translate(0,-50%);
    -o-transform: translate(0,-50%);
    transform: translate(0,-50%);
    top: 50%;
    margin: 0 auto;
}

http://www.codeply.com/go/14Ki1kyTgo

2018年更新

从Bootstrap 4 Beta 3开始,有一个新的modal-dialog-centered类可用,可以代替上述自定义方法。

https://www.codeply.com/go/lpOtIFoN6E (Beta 3)


那肯定是有效的。我可以问一下为什么还需要 translate(0,-50%); 吗? - wonderful world
这是一种垂直居中的“技巧”(http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/)。当元素(模态框)的高度未知时,它会查找视口的中心(`top: 50%transform: translateY(-50%)`)。 - Carol Skelly
@wonderfulworld,注意在比视口更高的模态框上使用此居中方法会导致模态框的顶部部分无法访问。 - tao
我不知道为什么,但这个修复在iPhone 6+的Chrome上不起作用。 - Evgenii

3

使用Flexbox,将Bootstrap 4模态弹出窗口垂直对齐非常容易。以下是CSS代码。

查看演示

SASS

.modal-open .modal.modal-center {
    display: flex!important;
    align-items: center!important;
    .modal-dialog {
        flex-grow: 1;
    }
}

编译后的CSS

.modal-open .modal.modal-center {
  display: -webkit-box !important;
  display: -ms-flexbox !important;
  display: flex !important;
  -webkit-box-align: center !important;
      -ms-flex-align: center !important;
          align-items: center !important;
}
.modal-open .modal.modal-center .modal-dialog {
  -webkit-box-flex: 1;
      -ms-flex-positive: 1;
          flex-grow: 1;
}

查看演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接