我如何在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之外的空间,以均匀分布(收缩直到容器宽度等于一列)。


当前回答

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

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

其他回答

Bootstrap 3现在有一个内置的类。center-block

.center-block {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

如果你还在用2。X然后把它添加到你的CSS。

正如koala_dev在他的方法1中使用的那样,我更喜欢offset方法,而不是使用有限的center-block或margin方法,但正如他提到的:

现在,这种方法有一个明显的缺点,它只适用于相同大小的列,因此只支持.col- x -2, .col- x -4, col-X-6, col-X-8和col-X-10。

对于奇数列,可以使用以下方法求解。

<div class="col-xs-offset-5 col-xs-2">
    <div class="col-xs-offset-3">
        // Your content here
    </div>
</div>

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

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

你可以使用文本中心的行,并可以确保内部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/

如果你把它放在你的行上,里面的所有列都将居中:

.row-centered {
    display: flex;
    justify-content: space-between;
}