引导程序: 如何在列内居中对齐内容?

一个简单的用例场景是使用一个图像或 Bootstrap 列中的任何其他内容。通常这些内容需要水平居中。

<div class="container">
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4 text-center">
<img class="img-responsive" src="img/some-image.png" title="this image needs to be centered">
</div>
<div class="col-sm-8 col-md-8 col-lg-8">
some content not important at this moment
</div>
</div>
</div>

在版本3.1.0中添加类文本中心在列内的图像居中。但是为了解决其他一些问题,我不得不转到3.3.4版本,而这种行为(文本中心)现在已经被打破了。 留给我的问题是如何在一个列中居中显示图像或其他内容。 我希望避免向包含的元素添加类,因为这很容易出错,或者需要另一个包含 div 的元素。

234277 次浏览

想要中心一个图像? 非常容易,Bootstrap 有两个类,.center-blocktext-center

在图像是 BLOCK元素的情况下使用前者,例如,将 img-responsive类添加到 img使得 img成为块元素。如果您知道如何在 Web 控制台中导航并查看元素的应用样式,那么您应该知道这一点。

不想用类吗?没问题,这里是 CSS 引导程序使用的。可以为元素创建自定义类或编写与 Bootstrap 类匹配的 CSS 规则。

 // In case you're dealing with a block element apply this to the element itself
.center-block {
margin-left:auto;
margin-right:auto;
display:block;
}


// In case you're dealing with a inline element apply this to the parent
.text-center {
text-align:center
}

可以通过添加一个 div (即 centerBlock)来实现这一点。并在 CSS 中赋予此属性以使图像或任何内容居中。密码如下:

<div class="container">
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4">
<div class="centerBlock">
<img class="img-responsive" src="img/some-image.png" title="This image needs to be centered">
</div>
</div>
<div class="col-sm-8 col-md-8 col-lg-8">
Some content not important at this moment
</div>
</div>
</div>




// CSS


.centerBlock {
display: table;
margin: auto;
}