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


当前回答

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

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

其他回答

正如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>

您可以使用非常灵活的解决方案flexbox到您的Bootstrap。

justify-content: center;

可以居中你的列。

看看flex。

使用bootstrap 4,你可以简单地尝试这里提到的justification -content-md-center

<div class="container">
    <div class="row justify-content-md-center">
        <div class="col col-lg-2">
              1 of 3
        </div>
        <div class="col-md-auto">
            Variable width content
        </div>
        <div class="col col-lg-2">
              3 of 3
        </div>
    </div>
    <div class="row">
        <div class="col">
             1 of 3
        </div>
        <div class="col-md-auto">
                Variable width content
        </div>
        <div class="col col-lg-2">
              3 of 3
        </div>
    </div>
</div>

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

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