How to center a div with Bootstrap2?

Alex picture Alex · Feb 21, 2012 · Viewed 332.4k times · Source

http://twitter.github.com/bootstrap/scaffolding.html

I tried like all combinations:

<div class="row">
  <div class="span7 offset5"> box </div>
</div>

or

<div class="container">
  <div class="row">
    <div class="span7 offset5"> box </div>
  </div>  
</div>

changed span and offset numbers...

But I cant get a simple box perfectly centered on a page :(

I just want a 6-column-wide box centered...


edit:

did it with

<div class="container">
  <div class="row" id="login-container">
    <div class="span8 offset2">
       box
    </div>
  </div>
</div>

But the box is too wide, is there any way I can do it with span7 ?

span7 offset2 gives extra padding to the left span7 offset3 extra padding to the right...

Answer

Zuhaib Ali picture Zuhaib Ali · Feb 18, 2013

Bootstrap's spans are floated to the left. All it takes to center them is override this behavior. I do this by adding this to my stylesheet:

.center {
     float: none;
     margin-left: auto;
     margin-right: auto;
}

If you have this class defined, just add it to the span and you're good to go.

<div class="span7 center"> box </div>

Note that this custom center class must be defined after the bootstrap css. You could use !important but that isn't recommended.