There are two approaches to centering a column <div>
in Bootstrap 3:
(有两种方法可以使Bootstrap 3中的列<div>
居中:)
Approach 1 (offsets): (方法1(偏移):)
The first approach uses Bootstrap's own offset classes so it requires no change in markup and no extra CSS.
(第一种方法使用Bootstrap自己的偏移量类,因此不需要更改标记,也不需要额外的CSS。)
The key is to set an offset equal to half of the remaining size of the row . (关键是将偏移量设置为等于行剩余大小的一半 。)
So for example, a column of size 2 would be centered by adding an offset of 5, that's (12-2)/2
. (因此,例如,大小为2的列将通过添加偏移量5(即(12-2)/2
居中。)
In markup this would look like:
(在标记中,它看起来像:)
<div class="row">
<div class="col-md-2 col-md-offset-5"></div>
</div>
Now, there's an obvious drawback for this method.
(现在,此方法有一个明显的缺点。)
It only works for even column sizes , so only .col-X-2
, .col-X-4
, col-X-6
, col-X-8
, and col-X-10
are supported. (它仅适用于偶数列大小 ,因此仅支持.col-X-2
, .col-X-4
, col-X-6
, col-X-8
和col-X-10
。)
Approach 2 (the old margin:auto
) (方法2(旧margin:auto
))
You can center any column size by using the proven margin: 0 auto;
(您可以使用已证明的margin: 0 auto;
将任何列大小居中 margin: 0 auto;
)
technique. (技术。)
You just need to take care of the floating that is added by Bootstrap's grid system. (您只需要注意由Bootstrap的网格系统添加的浮动即可。)
I recommend defining a custom CSS class like the following: (我建议定义一个自定义CSS类,如下所示:)
.col-centered{
float: none;
margin: 0 auto;
}
Now you can add it to any column size at any screen size, and it will work seamlessly with Bootstrap's responsive layout:
(现在,您可以将其添加到任何屏幕尺寸的任何列尺寸,并且它将与Bootstrap的响应式布局无缝协作:)
<div class="row">
<div class="col-lg-1 col-centered"></div>
</div>
Note: With both techniques you could skip the .row
element and have the column centered inside a .container
, but you would notice a minimal difference in the actual column size because of the padding in the container class.
(注意:两种方法都可以跳过.row
元素,并使列居中位于.container
内部,但是由于容器类中的填充,您会注意到实际列大小的最小差异。)
Update:
(更新:)
Since v3.0.1 Bootstrap has a built-in class named center-block
that uses margin: 0 auto
, but is missing float:none
, you can add that to your CSS to make it work with the grid system.
(由于v3.0.1 Bootstrap具有一个名为center-block
的内置类,该类使用margin: 0 auto
,但缺少float:none
,因此可以将其添加到CSS中以使其与网格系统一起使用。)