Bootstrap:如何在列内对齐内容?

时间:2015-05-29 10:07:51

标签: html css twitter-bootstrap

一个简单的用例场景是使用图像或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。

2 个答案:

答案 0 :(得分:76)

想要居中的形象?非常简单,Bootstrap有两个类,.center-blocktext-center

如果您的图片是BLOCK元素,请使用前者,例如,向img-responsive添加img类会使img成为块元素。如果您知道如何在Web控制台中导航并查看元素的应用样式,则应该知道这一点。

不想使用课程?没问题,这是CSS bootstrap使用的。您可以为该元素创建自定义类或编写CSS规则以匹配Bootstrap类。

 // 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
}

答案 1 :(得分:39)

您可以通过添加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;
}
相关问题