Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering bootstrap button group in an element

I am trying to figure out the best way to center a Bootstrap button group (i.e., btn-group) within an element. So, for example, if you have this:

<div id='toolbar'>
    <div class="btn-group">
        <button type="button" class="btn btn-default">Command1</button>
        <button type="button" class="btn btn-default">Command2</button>
    </div>
</div>

How might I ensure that the btn-group is always centered within toolbar (assuming it can fit)? The way I came up with is as follows: I wrap a div around the btn-group, figure out the width of that btn-group, and then set that width on the wrapper along with margin:0 auto. However, there are two things I don't like about this approach:

(1) It requires trial and error to figure out exactly what the width of the btn-group is, through setting a border on the wrapper and continually reducing it until you find the right width.

(2) If the width of the content changes even by a pixel (e.g., button text changes, or it just looks different on a different machine because of their font settings, etc.) then it's no longer centered and the second button drops down a line. Of course, you could leave a few pixels of leeway here, but then the two buttons wouldn't actually be fully centered in the first place.

There must be a better way. Any ideas? Here's my approach (jsfiddle):

html:

<div id='toolbar'>
    <div class='wrapper'>
        <div class="btn-group">
            <button type="button" class="btn btn-default">Command1</button>
            <button type="button" class="btn btn-default">Command2</button>
        </div>
    </div>
</div>

css:

#toolbar {
    width: 100%;
    max-width: 700px;
    margin: 10px;
    border: 1px solid black;
    padding: 10px;
}

#toolbar .wrapper {
    width: 197px;
    margin: 0 auto;
    /*border: 1px solid blue; used to test width*/
}
like image 843
EleventyOne Avatar asked Jan 27 '14 22:01

EleventyOne


2 Answers

Just use .text-center on the container since .btn-group is inline block: fiddle

<div id='toolbar'>
    <div class='wrapper text-center'>
        <div class="btn-group">
            <button type="button" class="btn btn-default">Command1</button>
            <button type="button" class="btn btn-default">Command2</button>
        </div>
    </div>
</div>
like image 70
Adrift Avatar answered Oct 03 '22 22:10

Adrift


Since the button group uses display: inline-block, the correct way to center them would be

#toolbar .wrapper {
    text-align: center;
}

http://jsfiddle.net/mblase75/USqQn/

(You can also apply the style to #toolbar and remove the div.wrapper entirely -- depending on whether you have anything else inside the toolbar. http://jsfiddle.net/mblase75/USqQn/1/)

like image 36
Blazemonger Avatar answered Oct 03 '22 22:10

Blazemonger