在twitter-bootstrap中居模态

时间:2013-08-15 16:30:13

标签: css twitter-bootstrap modal-dialog

我无法将我的模态集中在各种尺寸的twitter-bootstrap中。您可以看到实时示例herehere。 (只需点击图片或“报告此图片”)。你会看到模态就像魅力一样,但它不是水平居中的。我尝试了一切:边距,浮动,文本对齐甚至<center>

.modal:

.modal {
      position: fixed;
      top: 10%;
      z-index: 1050;
      width: auto;
      background-color: #ffffff;
      border: 1px solid #999;
      border: 1px solid rgba(0, 0, 0, 0.3);
      *border: 1px solid #999;
      -webkit-border-radius: 6px;
         -moz-border-radius: 6px;
              border-radius: 6px;
      outline: none;
      -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
         -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
              box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
      -webkit-background-clip: padding-box;
         -moz-background-clip: padding-box;
              background-clip: padding-box;
    }

.modal体:

.modal-body {
 margin: 0 auto 0 auto;
  position: relative;
  padding: 15px;
  overflow-y: auto;
}

6 个答案:

答案 0 :(得分:11)

我知道这有点晚了,但我找到了解决所有问题的方法,将Bootstrap Modal集中在不同于标准(一个)的高度。

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

答案 1 :(得分:6)

无论子元素大小(在本例中为模态)都能正常工作的解决方案。也可以用来垂直居中。

.centered {
    left: 50%;
    transform: translateX(-50%);
}

基本上我们在这里做的是将元素推到父容器宽度的一半。在模态的情况下,父母将(应该)是身体。 transform属性是将元素的 拥有 宽度的一半拉下来。

编辑:垂直居中

.centered {
    top: 50%;
    transform: translateY(-50%);
}

注意:我认为水平居中只有在父级的高度/宽度相同时才有效,因为%来自父级宽度。如果它们不相同,那么只需使用父高。

答案 2 :(得分:4)

这不是需要居中的模态体,而是整体模态。由于这有固定的定位,你可以使用CSS和jQuery(因为jQuery已被使用):

CSS:

.modal { left: 50%; }

jQuery的:

$('.modal').each(function(){
  var modalWidth = $(this).width(),
      modalMargin = '-' + (modalWidth/2) + 'px!important';
  $(this).css('margin-left',modalMargin);
});

或者只用CSS:

.modal { 
  width: 100%;
  left: 0;
  background-color: transparent; }

.modal-body { 
  display: inline-block; 
  background-color: #FFF; }

.modal img { min-width: none!important; }

答案 3 :(得分:2)

替代@ Coop的答案。由于你有一个固定宽度的文本区域,你可以设置模态的宽度并使用负边距而不是jquery。

.modal {
  left:50%;
  width:444px;
  margin-left:-222px;
}

在您当前的代码中,没有任何内容可以让模态居中。

答案 4 :(得分:2)

您可以使用jquery重现此行为:

left: 50%;
width: 560px;
margin-left: -280px;

计算div的宽度并指定css

$(document).ready(function () {

     var modalWidth = $('#myModal').width();
     $('#myModal').css("left", "50%");
     $('#myModal').css("width", modalWidth);
     $('#myModal').css("margin", (modalWidth/2)*-1);

});

答案 5 :(得分:1)

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