垂直居中引导模式窗口

Vertically centering Bootstrap modal window

本文关键字:窗口 模式 垂直居中      更新时间:2023-09-26

我想将我的模态居中放在视口上(中( 我尝试添加一些 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);
        }
    })

这完成了工作: 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>

.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;
}

因为 gpcola 的答案对我不起作用,所以我编辑了一下,所以它现在有效。我使用"边距顶部"而不是转换。此外,我使用"show"而不是"display"事件,因为它给了我一个非常糟糕的定位跳跃(当你打开引导动画时可见(。请务必在定位之前将显示设置为"块",否则 $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));

这就是我为我的应用程序所做的。如果您查看引导程序中的以下类.css文件 .modal-dialog 的默认填充为 10px 和@media屏幕,(最小宽度:768px(.modal-dialog 的顶部填充设置为 30px。因此,在我的自定义 css 文件中,我将所有屏幕的顶部填充设置为 15%,而无需指定媒体屏幕宽度。希望这有帮助。

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

我为所有HTML5浏览器找到的最佳方法:

body.modal-open .modal {
    display: flex !important;
    height: 100%;
} 
body.modal-open .modal .modal-dialog {
    margin: auto;
}
<!-- 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;
}

从 Bootstrap 4 开始,添加了以下类,以便在没有 JavaScript 的情况下为您实现这一点。

modal-dialog-centered

您可以在此处找到他们的文档。

感谢 v.d 指出您需要将 .modal-dialog-center 添加到 .modal-dialog 以垂直居中模式。

这对我非常有效:

.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;
}

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

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

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

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

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;
}

您必须使用 [style] 选择器才能仅将样式应用于当前处于活动状态的模态上,而不是所有模态上。 .in本来会很棒,但它似乎只有在过渡完成后才添加,这为时已晚,并且会导致一些非常糟糕的过渡。 幸运的是,引导程序似乎总是在模态上应用样式属性,就像它开始显示一样,所以这有点笨拙,但它有效。

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

您可以使用:

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

使其垂直和水平居中。

您可以在 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/

最干净、最简单的方法是使用 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

优点:

  • 模态内容即使比设备高也能访问
  • 不使用display:table-cell(不适用于布局(
  • 不需要对默认引导 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>

注意:我打算让这个答案与 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);
  }
}

又一个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

需要进一步完善它。

对于那些使用angular-upi引导程序的人,可以根据上述信息添加以下类:

注意:不需要其他更改,它应解决所有模式。

// 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;
}

不需要我们JavaScript。Boostrap modal在出现时添加.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%;
}

.modal.in .modal-dialog {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

垂直居中将 .modal-dialog-居中添加到 .modal-dialog 以垂直居中模式

启动演示模式

<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalCenterTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

我的选择,只是一点 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;
}

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

使用:引导 3.3.4

只需将以下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;
}

基于Arany的回答,但也考虑了页面滚动。

(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));

我认为这是比Rens de Nobel的解决方案更干净的纯CSS解决方案。此外,这不会阻止通过单击外部关闭对话框。

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

只需使用 .modal-dialog 类将一些 CSS 类添加到 DIV 容器中,即可获得比引导 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.center 容器固定并正确定位。

.CSS

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

或者使用弹性框甚至更简单。

.CSS

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

这在 BS3 中有效,未在 v2 中测试。 它垂直居中模态。请注意,它将在那里过渡 - 如果您希望它只出现在位置编辑 CSS 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);
});
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)
    });

这采用了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);
});

为了将垂直模态居中添加到引导模态.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.即使你不需要分配选择器,它也会从文档中找到所有模态并使其垂直居中

2.To 避免中间一些特定的模态成为中心,您可以使用:not 选择器在点击事件中

*/

 $( "[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);
  });

从 米兰潘迪亚

使用这个使模态居中的简单脚本。

如果需要,可以设置自定义类(例如:.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;
}
这个问题

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

注意:
应省略 Bootstrap 推荐.modal-dialog div以便其正常工作(似乎不会破坏任何东西(。在Chrome 51和IE 11中测试。

CSS代码:

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

编辑:.modal-dialog 类允许您选择用户是否可以通过单击模式本身外部来关闭模式。大多数模态都有一个明确的"关闭"或"取消"按钮。使用此解决方法时,请记住这一点。

宽度和高度集中模态的最佳解决方案是,在 css add 和模态中添加这个"集中化"作为一个类。

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