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, like so:

class="mx-auto"

As for other users suggestion there are also native bootstrap classes available like:

class="text-center"
class="pagination-centered"

From the Bootstrap documentation:

Set an element to display: block and center via margin. Available as a mixin and class.

<div class="center-block">...</div>

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 demo of 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


Also, you should know the basics of flexbox and how to use it, since Bootstrap 4 now uses it natively.

Here is an excellent, fast-paced video tutorial by Brad Schiff

Here is a great cheat sheet


In Bootstrap 4, the centering methods have changed.

Horizontal Center in Bootstrap 4

  • text-center is still used for display:inline elements
  • mx-auto replaces center-block to center display:flex children
  • offset-* or mx-auto can be used to center grid columns

mx-auto (auto x-axis margins) will center display:block or display:flex elements that have a defined width, (%, vw, px, etc..). Flexbox is used by default on grid columns, so there are also various flexbox centering methods.

Demo Bootstrap 4 Horizontal Centering

For vertical centering in BS4 see https://stackoverflow.com/a/41464397


You may directly write into your CSS file like this:

.content {
  position: absolute;
  top: 50%;
  left:50%;
  transform: translate(-50%,-50%);
  }
<div class = "content" >
  
   <p> some text </p>
  </div>