A simple use case scenario is to use an image, or any other content inside a Bootstrap column. And often this content needs to be horizontally centered.
<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>
In version 3.1.0 adding class text-center centered the image inside column. But I was forced to go to version 3.3.4 in order to fix some other issues and this behavior (text-center) is now broken. I am left with the problem how to center an image or other content inside a column. I would like to avoid having to add class to contained elements as this is error prone or requires another containing div.
This question is related to
html
css
twitter-bootstrap
You can do this by adding a div i.e. centerBlock. And give this property in CSS to center the image or any content. Here is the code:
<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;
}
Want to center an image? Very easy, Bootstrap comes with two classes, .center-block
and text-center
.
Use the former in the case of your image being a BLOCK
element, for example, adding img-responsive
class to your img
makes the img
a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.
Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.
// 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
}
Source: Stackoverflow.com