Skip to content Skip to sidebar Skip to footer

Unable To Center Div On Bootstrap 3

I'm unable to center a lot of div since I upgrade my bootstrap from 2.1 to 3.0 For example with this code:

Solution 1:

In order to center a block level element using margin: 0 auto; it must also have a width that is smaller than its containing block (for the auto value to make sense) - because #container is spanning the width of its parent (the <body>) there is simply no margin to distribute.

An alernative approach to margin: 0 auto; would be to set .btn-toolbar to inline-block and then centering it by adding text-align: center; to its containing block. You can apply the same concept to the second example:

http://fiddle.jshell.net/52VtD/94/


Solution 2:

In this instance, margin:0 auto doesn't work because the width of the element is 100%. If you want it to work, you would have to set a width on the element:

.btn-toolbar {
    width: 50px;
    margin: 0px auto;
}

If you want to center the text and the button, you could add the class text-center to the parent element, in this case: .row. The styling of this class is simply text-align: center.

<div class="row text-center">
  ..
</div>

EXAMPLE HERE

As @Adrift points out, it would be much more efficient to center the element by making it inline-block, as you can use text-align:center as opposed to margin:0 auto and avoid having to set a fixed width on the element. This will ensure that the element is centered regardless of its width. (example here) - don't forget you can just add the class text-center to the parent for centering.

It's also worth noting that inline/inline-block elements respect white-space in the markup, and thus generate space if present. If you want to remove this space, see this answer.


Post a Comment for "Unable To Center Div On Bootstrap 3"