在元素中居中引导按钮组

时间:2014-01-27 22:16:28

标签: html css twitter-bootstrap twitter-bootstrap-3

我试图弄清楚在一个元素中居中一个Bootstrap按钮组(即btn-group)的最佳方法。所以,例如,如果你有这个:

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

我如何确保btn-group始终位于toolbar内(假设它适合)?我提出的方法如下:我在div周围包裹btn-group,找出btn-group的宽度,然后在包装器上设置该宽度和margin:0 auto 1}}。但是,我不喜欢这种方法有两件事:

(1)通过在包装器上设置边框并不断减小它直到找到合适的宽度,需要反复试验才能确切知道btn-group的宽度是什么。

(2)如果内容的宽度改变了一个像素(例如,按钮文本改变,或者由于它们的字体设置等而在不同的机器上看起来不同),那么它不再居中,第二个按钮掉下一条线。当然,你可以留下几个像素的余地,但是这两个按钮实际上并不是首先完全居中。

必须有更好的方法。有任何想法吗?这是我的方法(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*/
}

2 个答案:

答案 0 :(得分:23)

只需在容器上使用.text-center,因为.btn-group是内嵌块: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>

答案 1 :(得分:2)

由于按钮组使用display: inline-block,因此将它们居中的正确方法是

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

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

(您也可以将样式应用到#toolbar并完全删除div.wrapper - 具体取决于工具栏中是否还有其他内容。http://jsfiddle.net/mblase75/USqQn/1/