我如何在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版本3有一个.text-center类。

只需添加这个类:

text-center

它只会加载这个样式:

.text-center {
    text-align: center;
}

例子:

<div class="container-fluid">
  <div class="row text-center">
     <div class="col-md-12">
          Bootstrap 4 is coming....
      </div>
  </div>
</div>   

其他回答

这可能不是最好的答案,但有一个更有创意的解决方案。正如koala_dev所指出的,列偏移只适用于相等的列大小。然而,通过嵌套行,您也可以实现居中不均匀的列。

坚持最初的问题,你想要在12个网格中居中一列1。

将2的列居中,使其偏移5 创建一个嵌套行,这样在2列中就有了新的12列。 因为你想要居中1列,而1是2的“一半”(我们在步骤1中居中),现在你需要在嵌套行中居中一个6列,这很容易通过偏移3来实现。

例如:

<div class="container">
  <div class="row">
    <div class="col-md-offset-5 col-md-2">
      <div class="row">
        <div class="col-md-offset-3 col-md-6">
          centered column with that has an "original width" of 1 col
        </div>
      </div>
    </div>
  </div>
</div>

看到这里,请注意,你必须增加输出窗口的大小,以便太看到结果,否则列将自动换行。

我处理列居中的方法是对列使用display: inline-block,对父容器使用text-align: center。

你只需要将CSS类“居中”添加到行。

HTML:

<div class="container-fluid">
  <div class="row centered">
    <div class="col-sm-4 col-md-4">
        Col 1
    </div>
    <div class="col-sm-4 col-md-4">
        Col 2
    </div>
    <div class="col-sm-4 col-md-4">
        Col 3
    </div>
  </div>
</div>

CSS:

.centered {
   text-align: center;
   font-size: 0;
}
.centered > div {
   float: none;
   display: inline-block;
   text-align: left;
   font-size: 13px;
}

JSFiddle: http://jsfiddle.net/steyffi/ug4fzcjd/

另一种抵消的方法是有两个空列,例如:

<div class="col-md-4"></div>
<div class="col-md-4">Centered Content</div>
<div class="col-md-4"></div>

注意,如果你正在使用Bootstrap 4,你可以在你的行中使用.align-items-center,因为Bootstrap 4现在使用flex系统。

你可以使用文本中心的行,并可以确保内部divs有display:inline-block(与不浮动)。

As:

<div class="container">
    <div class="row text-center" style="background-color : black;">
        <div class="redBlock">A red block</div>
        <div class="whiteBlock">A white block</div>
        <div class="yellowBlock">A yellow block</div>
    </div>
</div>

和CSS:

.redBlock {
    width: 100px;
    height: 100px;
    background-color: aqua;
    display: inline-block
}
.whiteBlock {
    width: 100px;
    height: 100px;
    background-color: white;
    display: inline-block
}
.yellowBlock {
    width: 100px;
    height: 100px;
    background-color: yellow;
    display: inline-block
}

小提琴: http://jsfiddle.net/DTcHh/3177/