【问题标题】:Bootstrap 3 modal vertical position centerBootstrap 3模态垂直位置中心
【发布时间】:2020-11-23 22:41:05
【问题描述】:

这是一个两部分的问题:

  1. 如果不知道模态框的确切高度,如何将模态框垂直定位在中心?

  2. 是否可以让模态框居中并在模态框体中有溢出:自动,但前提是模态框超出屏幕高度?

我试过用这个:

.modal-dialog {
  height: 80% !important;
  padding-top:10%;
}

.modal-content {
  height: 100% !important;
  overflow:visible;
}

.modal-body {
  height: 80%;
  overflow: auto;
}

当内容远大于垂直屏幕尺寸时,这给了我所需的结果,但对于小的模态内容,它几乎无法使用。

【问题讨论】:

  • @Heiken 出于某种原因这让我跳到屏幕上,我正在使用 chrome

标签: css twitter-bootstrap modal-dialog center


【解决方案1】:
.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;
}

并稍微调整 .fade 类以确保它出现在窗口的顶部边框之外,而不是中心

【讨论】:

  • 我实际上是错误地覆盖了它,感谢您指出它实际上在幕后工作。
  • 这可能是垂直居中的最佳方式,不仅是引导模式,还有其他一切。 css-tricks.com/centering-in-the-unknown
  • 我澄清这在移动设备上效果不佳。因为定义 ":after" 的高度为 100%,并且可以自动将模式移动到页面的下方。我刚刚解决了声明 .modal {display: flex!重要;} .modal-dialog {margin: auto}。 92.97% 的人已经支持使用这个 CSS 属性,但是对于一般支持者可以使用 JavaScript 来设置边距。
  • 绝对好,但我建议仅在 768 像素以上使用它,并在移动设备上保留默认设置。当屏幕高度较小时,顶部位置最适合模态框。我还调整了动画以使其从中心出现,如果有人需要,这里是工作示例:codepen.io/anon/pen/zGBpNq
  • 此解决方案将模态窗口向右移动 2px,导致 :before 元素。但这可以通过为 :after 添加相同的代码来解决
【解决方案2】:

1.不知道 modal 的准确高度时,如何将 modal 垂直定位在中心?

要在不声明高度的情况下使 Bootstrap 3 模态绝对居中,您首先需要通过将以下内容添加到样式表来覆盖 Bootstrap CSS:

.modal-dialog-center { /* Edited classname 10/03/2014 */
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
}

这会将模态对话框的左上角定位在窗口的中心。

我们必须添加这个媒体查询,否则在小型设备上模态边距是错误的:

@media (max-width: 767px) {
  .modal-dialog-center { /* Edited classname 10/03/2014 */
    width: 100%;
  }
} 

现在我们需要用 JavaScript 调整它的位置。为此,我们给元素一个负的上边距和左边距,等于其高度和宽度的一半。在这个例子中,我们将使用 jQuery,因为它可以在 Bootstrap 中使用。

$('.modal').on('shown.bs.modal', function() {
    $(this).find('.modal-dialog').css({
        'margin-top': function () {
            return -($(this).outerHeight() / 2);
        },
        'margin-left': function () {
            return -($(this).outerWidth() / 2);
        }
    });
});

更新(2015 年 1 月 10 日):

添加Finik's answer。感谢Centering in the Unknown

.modal {
  text-align: center;
  padding: 0!important;
}

.modal:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -4px; /* Adjusts for spacing */
}

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}

注意负边距对吗?这将删除内联块添加的空间。该空间导致模态框跳转到页面底部@media width

2。是否可以使模态居中并在模态主体中具有溢出:自动,但前提是模态超出屏幕高度?

这可以通过给 modal-body 一个 overflow-y:auto 和一个 max-height 来实现。这需要更多的工作才能使其正常工作。首先将其添加到您的样式表中:

.modal-body {
    overflow-y: auto;
}
.modal-footer {
    margin-top: 0;
}

我们将再次使用 jQuery 来获取窗口高度并首先设置 modal-content 的最大高度。然后我们必须设置 modal-body 的最大高度,方法是用 modal-header 和 modal-footer 减去 modal-content:

$('.modal').on('shown.bs.modal', function() {
    var contentHeight = $(window).height() - 60;
    var headerHeight = $(this).find('.modal-header').outerHeight() || 2;
    var footerHeight = $(this).find('.modal-footer').outerHeight() || 2;

    $(this).find('.modal-content').css({
        'max-height': function () {
            return contentHeight;
        }
    });

    $(this).find('.modal-body').css({
        'max-height': function () {
            return (contentHeight - (headerHeight + footerHeight));
        }
    });

    $(this).find('.modal-dialog').css({
        'margin-top': function () {
            return -($(this).outerHeight() / 2);
        },
        'margin-left': function () {
            return -($(this).outerWidth() / 2);
        }
    });
});

您可以在此处找到使用 Bootstrap 3.0.3 的工作演示:http://cdpn.io/GwvrJ 编辑:我建议使用更新版本来获得响应更快的解决方案:http://cdpn.io/mKfCc

更新(2015 年 11 月 30 日):

function setModalMaxHeight(element) {
  this.$element     = $(element);  
  this.$content     = this.$element.find('.modal-content');
  var borderWidth   = this.$content.outerHeight() - this.$content.innerHeight();
  var dialogMargin  = $(window).width() < 768 ? 20 : 60;
  var contentHeight = $(window).height() - (dialogMargin + borderWidth);
  var headerHeight  = this.$element.find('.modal-header').outerHeight() || 0;
  var footerHeight  = this.$element.find('.modal-footer').outerHeight() || 0;
  var maxHeight     = contentHeight - (headerHeight + footerHeight);

  this.$content.css({
      'overflow': 'hidden'
  });

  this.$element
    .find('.modal-body').css({
      'max-height': maxHeight,
      'overflow-y': 'auto'
  });
}

$('.modal').on('show.bs.modal', function() {
  $(this).show();
  setModalMaxHeight(this);
});

$(window).resize(function() {
  if ($('.modal.in').length != 0) {
    setModalMaxHeight($('.modal.in'));
  }
});

(更新于 2015 年 11 月 30 日 http://cdpn.io/mKfCc 进行上述编辑)

【讨论】:

  • 优秀的答案和帖子!但是,这也可以动画吗?它刚弹出时效果很好,但是动画呢?我在工作,无法在atm测试它,但我渴望看到结果
  • 您可以在模态框上添加一个淡入淡出类。在cdpn.io/mKfCc查看我的更新解决方案
  • 虽然它似乎在 codepen 上运行良好,但我无法让它在我的项目中运行。我猜你只需要添加代码而不是替换一些东西对吗?
  • 你好!注意到以下内容。当第一个模态框第一次打开时,右边距是错误的,直到你调整一次。关于这个有什么想法吗?
  • @bernie 我用我的 codepen 的一个分支在 Browserstack 上制作了屏幕截图,它在 document.ready 上打开了短模式:browserstack.com/screenshots/… Browserstack 不支持 v9.3.x 的屏幕截图(还) ,但我认为在 iOS 6.0 上会发生与您所描述的类似的事情(请参见屏幕截图 iPad 3rd (6.0)(Portrait))。也许这是一个在 v9.3.2 中返回的旧错误。如果您愿意,可以在forums.developer.apple.com/community/safari-and-web/… 提交错误报告
【解决方案3】:

我的解决方案

.modal-dialog-center {
    margin-top: 25%;
}

    <div id="waitForm" class="modal">
        <div class="modal-dialog modal-dialog-center">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 id="headerBlock" class="modal-title"></h4>
                </div>
                <div class="modal-body">
                    <span id="bodyBlock"></span>
                    <br/>
                    <p style="text-align: center">
                        <img src="@Url.Content("~/Content/images/progress-loader.gif")" alt="progress"/>
                    </p>   
                </div>
            </div>
        </div>
    </div>

【讨论】:

  • 你应该使用 padding-top。当您单击叠加层时,margin 将中断关闭操作
  • 上边距设置为 25% 要求模态框高度为 50%。
【解决方案4】:

它可以简单地用display: flex修复

.modal-dialog {
  margin-top: 0;
  margin-bottom: 0;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.modal.fade .modal-dialog {
  transform: translate(0, -100%);
}

.modal.in .modal-dialog {
  transform: translate(0, 0);
}

带前缀

.modal-dialog {
  margin-top: 0;
  margin-bottom: 0;
  height: 100vh;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
      -ms-flex-direction: column;
          flex-direction: column;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
      -ms-flex-pack: center;
          justify-content: center;
}

.modal.fade .modal-dialog {
  -webkit-transform: translate(0, -100%);
          transform: translate(0, -100%);
}
.modal.in .modal-dialog {
  -webkit-transform: translate(0, 0);
          transform: translate(0, 0);
}

【讨论】:

  • 这可以防止背景被点击,因为高度为 100vh。 “背景:'静态'”设置很好。
  • 这会导致动画淡出问题
【解决方案5】:

如果你对使用 flexbox 没问题,那么这应该有助于解决它。

.modal-dialog {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
}

.modal-content {
  margin: 0 auto;
}

【讨论】:

  • 我发现这个答案对我很有用。但是,如果您想让用户通过单击其背景来关闭模态框,请确保将 pointer-events: none 添加到 .modal-dialogpointer-events: auto.modal-content。因为.modal-dialog {height: 100%} 覆盖了模式上方和下方的整个列,并禁止用户单击该区域的背景。
  • 结合@ChingTingWu 的建议,最有效
  • 那么@ChingTingWu 的建议呢?
  • ChingTingWu 好像改成了@wuct
  • @giovannipds 哎呀,我重命名了我的用户名,因为它更短更容易被标记。很抱歉造成混淆:)
【解决方案6】:

我想出了一个纯 CSS 解决方案!虽然它是 css3,这意味着不支持 ie8 或更低版本,但除此之外,它已经过测试并可以在 ios、android、ie9+、chrome、firefox、桌面 safari 上运行。

我正在使用以下 css:

.modal-dialog {
  position:absolute;
  top:50% !important;
  transform: translate(0, -50%) !important;
  -ms-transform: translate(0, -50%) !important;
  -webkit-transform: translate(0, -50%) !important;
  margin:auto 5%;
  width:90%;
  height:80%;
}
.modal-content {
  min-height:100%;
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0; 
}
.modal-body {
  position:absolute;
  top:45px; /** height of header **/
  bottom:45px;  /** height of footer **/
  left:0;
  right:0;
  overflow-y:auto;
}
.modal-footer {
  position:absolute;
  bottom:0;
  left:0;
  right:0;
}

这是一个小提琴。 http://codepen.io/anon/pen/Hiskj

..选择这个作为正确答案,因为没有额外的繁重的 javascript 在多个模式的情况下使浏览器崩溃。

【讨论】:

  • 使用 JavaScript 的重点是获取模态框的 unknown 高度。您的解决方案具有 80% 的固定高度,这不能回答您自己的问题:“当您不知道模态框的确切高度时,如何将模态框垂直定位在中心? "
  • ...高度尺寸设置为限制与屏幕高度相比的最大模态高度。但是,翻译的百分比是根据 CONTENT 高度设置的。
  • 如果你想得到一个不改变模态框大小的解决方案,也可以试试下面的 css 解决方案:tweaks.klickagent.ch/#30.05.2014_TwitterBootstrapCenterModal
  • 也很好。但是,它的方法与我所描述的方法不同。在您的情况下,整个模式上下移动,而在我的情况下,创建了一个溢出的元素。不过非常好!我喜欢!
  • 这需要设置高度。这与用户要求的不完全相同。
【解决方案7】:

我的解决方案:

.modal.in .modal-dialog 
{
    -webkit-transform: translate(0, calc(50vh - 50%));
    -ms-transform: translate(0, 50vh) translate(0, -50%);
    -o-transform: translate(0, calc(50vh - 50%));
    transform: translate(0, 50vh) translate(0, -50%);
}

【讨论】:

  • 这似乎与 Bootstrap 3 完美配合。为什么这不是公认的答案?它比其他的要简单得多(4 个 css 指令)。
  • @danielricecodes 我要试一试,假设是因为the issues with viewport units.。 scooterlord 提出的答案提出了与 IE9 和 iO 的兼容性,这对我来说是一个问题。如果您查看 canIuse 的问题页面,您会看到 iO 和 IE10 及更早版本存在问题。并不是说我同意或不同意这是正确的答案。我只是指出为什么也许这没有被选为答案。
  • 这种方法的一个问题是当模式具有可滚动的内容时(内容多于适合窗口的内容)
  • 这应该是公认的答案。到目前为止,这是唯一适合我的解决方案。谢谢你。
  • 如果您的模态内容大于屏幕高度(如果您的模态必须滚动),这将不起作用
【解决方案8】:

在我的案例中,我所做的只是在我的 css 中设置 Top 以了解模态的高度

&lt;div id="myModal" class="modal fade"&gt; ... &lt;/div&gt;

在我的 css 中设置

#myModal{
    height: 400px;
    top: calc(50% - 200px) !important;
}

【讨论】:

  • 作为一个 css 菜鸟,这个答案似乎最不可怕并且完成了工作
  • 这没有回答问题的第一部分:“..当您不知道模态框的确切高度时?”
【解决方案9】:

添加这个简单的 css 也可以。

.modal-dialog {
  height: 100vh !important;
  display: flex;
}

.modal-content {
  margin: auto !important;
  height: fit-content !important;
}

【讨论】:

  • 什么是适合内容?
【解决方案10】:

使用 css 有一个最简单的方法:

.modal-dialog {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    width:500px;
    height:300px;
}

就是这样。请注意,它只需要应用于.modal-dialog 容器div。

演示:https://jsfiddle.net/darioferrer/0ueu4dmy/

【讨论】:

  • 由于固定的宽度和高度,在移动设备上没有响应。
  • 您的答案假设每台设备都具有相同的屏幕分辨率
  • 没有人。我假设你理解了这个例子,并且你能够适应每种情况。
  • 在Bootstrap v3.3.0中运行成功,谢谢
【解决方案11】:

扩展 @Finik 的出色答案,此修复仅适用于非移动设备。我在 IE8、Chrome 和 Firefox 22 中进行了测试 - 它适用于很长或很短的内容。

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

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}

【讨论】:

    【解决方案12】:

    我写的最通用的解决方案。动态计算对话高度。 (下一步可能是在调整窗口大小时重新计算对话框的高度。)

    JSfiddle:http://jsfiddle.net/8Fvg9/3/

    // initialise on document ready
    jQuery(document).ready(function ($) {
        'use strict';
    
        // CENTERED MODALS
        // phase one - store every dialog's height
        $('.modal').each(function () {
            var t = $(this),
                d = t.find('.modal-dialog'),
                fadeClass = (t.is('.fade') ? 'fade' : '');
            // render dialog
            t.removeClass('fade')
                .addClass('invisible')
                .css('display', 'block');
            // read and store dialog height
            d.data('height', d.height());
            // hide dialog again
            t.css('display', '')
                .removeClass('invisible')
                .addClass(fadeClass);
        });
        // phase two - set margin-top on every dialog show
        $('.modal').on('show.bs.modal', function () {
            var t = $(this),
                d = t.find('.modal-dialog'),
                dh = d.data('height'),
                w = $(window).width(),
                h = $(window).height();
            // if it is desktop & dialog is lower than viewport
            // (set your own values)
            if (w > 380 && (dh + 60) < h) {
                d.css('margin-top', Math.round(0.96 * (h - dh) / 2));
            } else {
                d.css('margin-top', '');
            }
        });
    
    });
    

    【讨论】:

      【解决方案13】:

      here找到完美解决方案

      $(function() {
          function reposition() {
              var modal = $(this),
                  dialog = modal.find('.modal-dialog');
              modal.css('display', 'block');
      
              // Dividing by two centers the modal exactly, but dividing by three 
              // or four works better for larger screens.
              dialog.css("margin-top", Math.max(0, ($(window).height() - dialog.height()) / 2));
          }
          // Reposition when a modal is shown
          $('.modal').on('show.bs.modal', reposition);
          // Reposition when the window is resized
          $(window).on('resize', function() {
              $('.modal:visible').each(reposition);
          });
      });
      

      【讨论】:

      • 谢谢。非常适合我的一个更改: dialog.css("margin-top", Math.max(0, ($(document).scrollTop() + (($(window).height() - dialog.height()) / 2))));
      【解决方案14】:

      这是相当古老的,专门要求使用 Bootstrap 3 的解决方案,但对于任何想知道的人:从 Bootstrap 4 开始,有一个名为 .modal-dialog-centered 的内置解决方案。这是问题所在:https://github.com/twbs/bootstrap/issues/23638

      因此,使用 v4 时,您只需将 .modal-dialog-centered 添加到 .modal-dialog 即可使模态垂直居中:

      <!-- Button trigger modal -->
      <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
        Launch demo modal
      </button>
      
      <!-- 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>
      

      Demo

      【讨论】:

        【解决方案15】:
        $('#myModal').on('shown.bs.modal', function() {
            var initModalHeight = $('#modal-dialog').outerHeight(); //give an id to .mobile-dialog
            var userScreenHeight = $(document).outerHeight();
            if (initModalHeight > userScreenHeight) {
                $('#modal-dialog').css('overflow', 'auto'); //set to overflow if no fit
            } else {
                $('#modal-dialog').css('margin-top', 
                (userScreenHeight / 2) - (initModalHeight/2)); //center it if it does fit
            }
        });
        

        【讨论】:

        • 对选择器进行了一些调整,这就像一个魅力。 @$modal = $('.fade.in'); modalBox = @$modal.find('.modal-content'); initModalHeight = modalBox.outerHeight(); userScreenHeight = @$modal.outerHeight()
        【解决方案16】:

        这是另一种仅使用 css 的方法,效果很好,并且基于此: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

        萨斯:

        .modal {
            height: 100%;
        
            .modal-dialog {
                top: 50% !important;
                margin-top:0;
                margin-bottom:0;
            }
        
            //keep proper transitions on fade in
            &.fade .modal-dialog {
                transform: translateY(-100%) !important;
            }
            &.in .modal-dialog {
                transform: translateY(-50%) !important;
            }
        }
        

        【讨论】:

        • 与其他 transform 解决方案一样,当模式具有可滚动内容(内容多于窗口中的内容)时,就会出现问题
        【解决方案17】:

        这对我有用:

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

        【讨论】:

          【解决方案18】:

          我已经从下面的链接下载了 bootstrap3-dialog 并修改了 bootstrap-dialog.js 中的 open 函数

          https://github.com/nakupanda/bootstrap3-dialog

          代码

          open: function () {
                      !this.isRealized() && this.realize();
                      this.updateClosable();
                      //Custom To Vertically centering Bootstrap 
                      var $mymodal = this.getModal();
                      $mymodal = $mymodal.append('<table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%"><tr><td align="center" valign="middle" class="centerModal"></td></tr></table>');
                      $mymodal = $mymodal.find(".modal-dialog").appendTo($mymodal.find(".centerModal"));
                      //END
                      this.getModal().modal('show');
                      return this;
                  }
          

          CSS

          .centerModal .modal-header{
              text-align:left;
          }
          .centerModal .modal-body{
              text-align:left;
          } 
          

          【讨论】:

          • 这里有一个修改可以应用到你自己的代码中,而不必改变原始的 BSDialog 源:gist.github.com/mahemoff/8ff6d3782d2da6f9cbb3(只是对 JS 的一些修改,也是用 Coffee 编写的,但你明白了)。
          【解决方案19】:

          试试这样的:

          .popup__overlay {
              position: fixed;
              left:  0;
              top:  0;
              width: 100%;
              height: 100%;
              z-index: 999;
              text-align: center
              }
          .popup {
              display: inline-block;
              vertical-align: middle
              } 
          

          【讨论】:

          • 这可以很好地工作,但引导模式有绝对值,内部固定,内部这个和那个......:/
          • 这些类与 Bootstrap / Bootstrap modals 有什么关系?
          【解决方案20】:

          您可能想查看这个绝对居中 div 的方法集合:http://codepen.io/shshaw/full/gEiDt

          【讨论】:

          • 嗯,它在警告中说你必须声明高度,这不是我要找的
          【解决方案21】:

          一个简单的方法。为我工作。谢谢rensdenobel :) http://jsfiddle.net/rensdenobel/sRmLV/13/

          <style>
          .vertical-alignment-helper {
              display:table;
              height: 100%;
              width: 100%;
          }
          .vertical-align-center {
              /* To center vertically */
              display: table-cell;
              vertical-align: middle;
          }
          .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;
          }
          </style>
          <!-- Button trigger modal -->
          <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>    
          

          【讨论】:

            【解决方案22】:

            另一种解决方案,它将在window.resize 事件和show.bs.modal 上为每个可见模式设置一个有效位置:

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

            【讨论】:

              【解决方案23】:
              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);
              

              【讨论】:

                【解决方案24】:

                我知道这有点晚了,但我正在添加一个新答案,以免它迷失在人群中。这是一个跨桌面-移动-浏览器的解决方案,可以在任何地方正常工作。

                它只需要将modal-dialog 包装在modal-dialog-wrap 类中,并且需要添加以下代码:

                .modal-dialog-wrap {
                  display: table;
                  table-layout: fixed;
                  width: 100%;
                  height: 100%;
                }
                
                .modal-dialog {
                  display: table-cell;
                  vertical-align: middle;
                  text-align: center;
                }
                
                .modal-content {
                  display: inline-block;
                  text-align: left;
                }
                

                对话框从中心开始,如果内容很大,它会垂直增长,直到出现滚动条。

                这是一个让您高兴的工作小提琴!

                https://jsfiddle.net/v6u82mvu/1/

                【讨论】:

                  【解决方案25】:

                  .modal {
                  }
                  .vertical-alignment-helper {
                      display:table;
                      height: 100%;
                      width: 100%;
                  }
                  .vertical-align-center {
                      /* To center vertically */
                      display: table-cell;
                      vertical-align: middle;
                  }
                  .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;
                  }
                  <head>
                  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
                  
                  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
                  <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
                  </head>
                  
                  <body>
                  <!-- Button trigger modal -->
                  <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>
                  </body>

                  CSS:

                  .modal {
                  }
                  .vertical-alignment-helper {
                      display:table;
                      height: 100%;
                      width: 100%;
                  }
                  .vertical-align-center {
                      /* To center vertically */
                      display: table-cell;
                      vertical-align: middle;
                  }
                  .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;
                  }
                  

                  HTML:

                  <!-- Button trigger modal -->
                  <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>
                  

                  参考:http://jsfiddle.net/rensdenobel/sRmLV/13/

                  【讨论】:

                    【解决方案26】:

                    考虑使用此处的引导模式插件 - https://github.com/jschr/bootstrap-modal

                    该插件将使您的所有模式居中

                    【讨论】:

                    • ...不幸的是,我已经尝试过,但无法使其正常工作——至少不是我的代码。我想每个人都需要根据自己的需要定制这个!不过感谢您的回复。
                    【解决方案27】:

                    对于居中,我不明白过于复杂的解决方案是什么。 bootstrap 已经为你水平居中,所以你不需要弄乱这个。我的解决方案是仅使用 jQuery 设置上边距。

                    $('#myModal').on('loaded.bs.modal', function() {
                        $(this).find('.modal-dialog').css({
                            'margin-top': function () {
                                return (($(window).outerHeight() / 2) - ($(this).outerHeight() / 2));
                            }
                        });
                    });
                    

                    我在远程加载内容时使用了 loaded.bs.modal 事件,而使用 shown.ba.modal 事件会导致高度计算不正确。如果您需要它具有响应性,您当然可以为正在调整大小的窗口添加一个事件。

                    【讨论】:

                    • 如果模态足够大,可能会导致问题
                    【解决方案28】:

                    实现这一概念的非常简单的方法,您将始终通过 css 在屏幕的模式中获得模态:http://jsfiddle.net/jy0zc2jc/1/

                    您必须通过以下 css 将 modal 类显示为表格:

                    display:table
                    

                    modal-dialog 作为display:table-cell

                    在给定的小提琴中查看完整的工作示例

                    【讨论】:

                    • 我根本没有看到模式
                    • 我看到的唯一东西(在谷歌浏览器中)是一个红十字图标和背景
                    • 当模式的内容多于窗口的内容时,不滚动标签
                    【解决方案29】:

                    没那么复杂。

                    请试试这个:

                    $(document).ready(function(){
                        var modalId = "#myModal";
                        resize: function(){
                                var new_margin = Math.ceil(($(window).height() - $(modalId).find('.modal-dialog').height()) / 2);
                                $(modalId).find('.modal-dialog').css('margin-top', new_margin + 'px');
                        }
                        $(window).resize(function(){
                            resize();
                        });
                        $(modalId).on('shown.bs.modal', function(){
                            resize();
                        });
                    });
                    

                    【讨论】:

                      【解决方案30】:

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

                      如果您愿意,您可以设置一个自定义类(例如:.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 修复;我们在 modals 上显示滚动,Bootstrap 会自动隐藏 body 滚动:

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

                      【讨论】:

                        猜你喜欢
                        • 2013-10-03
                        • 2013-12-17
                        • 1970-01-01
                        • 2014-03-07
                        • 2014-01-29
                        • 1970-01-01
                        • 2011-02-13
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多