Twitter Bootstrap - how to center elements horizontally or vertically
Update: while this answer was likely correct back in early 2013, it should not be used anymore. The proper solution uses offsets.
As for other users suggestion there are also native bootstrap classes available like:
class="text-center"
class="pagination-centered"
thanks to @Henning and @trejder
From the Bootstrap documentation:
Set an element to
display: block
and center viamargin
. Available as a mixin and class.
<div class="center-block">...</div>
For future visitors to this question:
If you are trying to center an image in a div but the image won't center, this could describe your problem:
jsFiddle DEMO of the problem
<div class="col-sm-4 text-center">
<img class="img-responsive text-center" src="myPic.jpg" />
</div>
The img-responsive
class adds a display:block
instruction to the image tag, which stops text-align:center
(text-center
class) from working.
SOLUTION:
<div class="col-sm-4">
<img class="img-responsive center-block" src="myPic.jpg" />
</div>
jsFiddle of the solution
Adding the center-block
class overrides the display:block
instruction put in by using the img-responsive
class.
Without the img-responsive
class, the image would center just by adding text-center
class
Update:
Also, you should know the basics of flexbox and how to use it, since Bootstrap4 now uses it natively.
Here is an excellent, fast-paced video tutorial by Brad Schiff
Here is a great cheat sheet