我如何在Twitter Bootstrap 3的容器(12列)中心一个列大小的div ?

.centered { 背景颜色:红色; } <!——最新编译和最小化的CSS——> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="匿名"> <身体类= "容器" > <div class=" font - family -宋体"> <img data-src="holder.js/100x100" alt="" /> . < / div > 身体< / >

我想要一个div,类。居中在容器中。如果有多个div,我可能会使用一行,但现在我只想要一个div的大小为一列居中容器(12列)。

我也不确定上面的方法是否足够好,因为目的不是将div抵消一半。我不需要在div之外的自由空间和div的内容按比例缩小。我想清空div之外的空间,以均匀分布(收缩直到容器宽度等于一列)。


当前回答

更准确地说,Bootstrap的网格系统包含12列,为了将任何内容居中,例如,内容占用一列。需要占用Bootstrap网格的两列,并将内容放置在这两列的一半上。

<div class="row">
   <div class="col-xs-2 col-xs-offset-5 centered">
      ... your content / data will come here ...
   </div>
</div>

'col-xs-offset-5'告诉网格系统从哪里开始放置内容。

'col-xs-2'告诉网格系统内容应该占据多少剩余列。

' centric '将是一个定义的类,它将内容居中。

下面是这个例子在Bootstrap的网格系统中的样子。

列:

1 | 2 | 3 | 4 5 6 7 | | | | | 8 9 10 11 | | | 12

.......offset....... .data. .......不习惯……

其他回答

要在Bootstrap行中居中多个列-并且cols的数量是奇数,只需将这个css类添加到该行中的所有列:

.many-cols-centered {  // To horizontally center bootstrap odd cols, eg col-lg-9, col-md-3, works well in lg
  display:inline-block;
  float:none;
}

所以在你的HTML中,你有这样的东西:

<div class="row text-center"> <!-- text-center centers all text in that row -->
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image1.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image2.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image3.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
</div>

Bootstrap 4解决方案:

<div class="container">
  <div class="row">
    <div class="col align-self-center">
      Column in the middle, variable width
    </div>
  </div>
</div>

要居中的颜色-我们需要使用下面的代码。Cols是除保证金外的浮动元素。我们也将它设为浮点数为0,

<body class="container">
    <div class="col-lg-1 col-md-4 centered">
        <img data-src="holder.js/100x100" alt="" />
    </div>
</body>

为了使上面的col-lg-1的类居中,我们将写:

.centered {
    float: none;
    margin-left: auto;
    margin-right: auto;
}

要将div中的内容居中,请使用text-align:center,

.centered {
    text-align: center;
}

如果您只想在桌面和更大的屏幕上居中,而不是在移动设备上,则使用以下媒体查询。

@media (min-width: 768px) {
    .centered {
        float: none;
        margin-left: auto;
        margin-right: auto;
    }
}

并且只在移动版本上居中div,使用下面的代码。

@media (max-width: 768px) {
    .centered {
        float: none;
        margin-left: auto;
        margin-right: auto;
    }
}

我建议简单地使用类text-center:

<body class="container">
    <div class="col-md-12 text-center">
        <img data-src="holder.js/100x100" alt="" />
    </div>
</body>

这个作品。这可能是一种粗鄙的方式,但效果很好。它被测试为响应性(Y)。

.centered {
    background-color: teal;
    text-align: center;
}