Bootstrap是否支持固定宽度的按钮?目前,如果我有2个按钮,“保存”和“下载”,按钮大小根据内容而变化。

还有什么是正确的方式扩展Bootstrap?


当前回答

只是遇到了同样的需求,并没有满足于定义固定宽度。

jquery也是如此:

var max =数学。马克斯($ (" # share_cancel ")。Width (), $("#share_commit")。宽度()); $ (" # share_cancel”)。宽度(max); $ (" # share_commit”)。宽度(max); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <button type="button" class="btn btn-secondary" id="share_cancel">SHORT</button> . <button type="button" class="btn btn-success" id="share_commit">LOOOOOOOOONG</button>

其他回答

btn-group-justified和btn-group只适用于静态内容,但不适用于动态创建的按钮,在CSS中固定的按钮是不实际的,因为它保持相同的宽度,即使所有的内容都很短。

我的解决方案: 将相同的类放入按钮组,然后循环到所有按钮,获得最长按钮的宽度,并将其应用于所有按钮

var bwidth=0
$("button.btnGroup").each(function(i,v){
    if($(v).width()>bwidth) bwidth=$(v).width();
});
$("button.btnGroup").width(bwidth);

在这里,我通过比较按钮组元素中的按钮找到了一个解决方案。简单的解决方法是获取宽度最大的按钮,并将宽度设置为其他按钮。所以它们的宽度是相等的。

    function EqualizeButtons(parentElementId) {

    var longest = 0; 
    var element = $(parentElementId);

    element.find(".btn:not(.button-controlled)").each(function () {
        $(this).addClass('button-controlled');
        var width = $(this).width();
        if (longest < width) longest = width;

    }).promise().done(function () {
        $('.button-controlled').width(longest);
    });
}

这招很管用。

对于bs4和bs5,您还可以使用大小调整,并应用w-100,以便按钮可以占用父容器的完整宽度。

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> Using btn-block </p> <div class="container-fluid"> <div class="btn-group col" role="group" aria-label="Basic example"> <button type="button" class="btn btn-outline-secondary">Left</button> <button type="button" class="btn btn-outline-secondary btn-block">Middle</button> <button type="button" class="btn btn-outline-secondary">Right</button> </div> </div> <p> Using w-100 </p> <div class="container-fluid"> <div class="btn-group col" role="group" aria-label="Basic example"> <button type="button" class="btn btn-outline-secondary">Left</button> <button type="button" class="btn btn-outline-secondary w-100">Middle</button> <button type="button" class="btn btn-outline-secondary">Right</button> </div> </div>

如果父容器是响应式的,那么块宽度按钮很容易变成响应式按钮。我认为使用固定宽度和更详细的选择器路径的组合而不是!很重要,因为:

1)这不是一个hack(设置min-width和max-width相同是hack)

2)不使用!important标签,这是不好的做法

3)使用宽度,因此将非常可读,任何了解CSS中的级联工作原理的人都将看到发生了什么(可能会为此留下CSS评论?)

4)结合你的选择器,适用于你的目标节点,以提高准确性

.parent_element .btn.btn-primary.save-button {
    width: 80px;
}

这可能是一个愚蠢的解决方案,但我一直在寻找这个问题的解决方案,结果懒惰了。

总之,使用input class="btn…"... 用空格代替button和填充value=属性,这样它们的宽度都是一样的,效果很好。

例如:

<input type="submit" class="btn btn-primary" value="   Calculate   "/>    
<input type="reset" class="btn btn-primary"value="     Reset       "/>

我还没有使用bootstrap很长时间,也许有一个很好的理由不使用这种方法,但我认为我最好分享一下