How do I center a Bootstrap div with a 'spanX' class?
Twitter's bootstrap .span
classes are floated to the left so they won't center by usual means. So, if you want it to center your span
simply add float:none
to your #main
rule.
CSS
#main {
margin:0 auto;
float:none;
}
If anyone wants the true solution for centering BOTH images and text within a span using bootstrap row-fluid, here it is (how to implement this and explanation follows my example):
css
div.row-fluid [class*="span"] .center-in-span {
float: none;
margin: 0 auto;
text-align: center;
display: block;
width: auto;
height: auto;
}
html
<div class="row-fluid">
<div class="span12">
<img class="center-in-span" alt="MyExample" src="/path/to/example.jpg"/>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<p class="center-in-span">this is text</p>
</div>
</div>
USAGE: To use this css to center an image within a span, simply apply the .center-in-span class to the img element, as shown above.
To use this css to center text within a span, simply apply the .center-in-span class to the p element, as shown above.
EXPLANATION: This css works because we are overriding specific bootstrap styling. The notable differences from the other answers that were posted are that the width and height are set to auto, so you don't have to used a fixed with (good for a dynamic webpage). also, the combination of setting the margin to auto, text-align:center and display:block, takes care of both images and paragraphs.
Let me know if this is thorough enough for easy implementation.
Incidentally, if your span
class is even-numbered (e.g. span8
) you can add an offset
class to center it – for span8
that would be offset2
(assuming the default 12-column grid), for span6
it would be offset3
and so on (basically, half the number of remaining columns if you subtract the span
-number from the total number of columns in the grid).
UPDATE
Bootstrap 3 renamed a lot of classes so all the span*
classes should be col-md-*
and the offset
classes should be col-md-offset-*
, assuming you're using the medium-sized responsive grid.
I created a quick demo here, hope it helps: http://codepen.io/anon/pen/BEyHd.