繁体   English   中英

如何将最长元素的宽度分配给其他元素

[英]How assign the width of the longest element to other elements

我有以下要素

在此处输入图片说明

练习名称是动态的,因此包含练习名称的按钮的宽度会有所不同,但是随附的颜色按钮是固定宽度的。 父元素的width: auto; height: auto width: auto; height: auto无论运动名称有多长, width: auto; height: auto都会适合任何按钮。

如何使所有按钮的长度等于最宽的练习名称按钮的宽度?

或类似地, 即使选择了更长的练习名称,我如何也可以使这些按钮对齐但不会溢出。

如果仅在CSS中寻找解决方案,则有一种方法可以将display属性用作tabletable-rowtable-cell 我认为您可以将其扩展用于标记:

 .btn-container { display: table; border: 1px #000 solid !important; } .btn { display: table-row; } .btn-text { display: table-cell; padding: 3px; } .btn-label { width: 30px; display: table-cell; } .btn-label-red { background: #F00; } .btn-label-green { background: #0F0; } .btn-label-blue { background: #00F; } 
 <div class="btn-container"> <div class="btn"> <span class="btn-text">Button 1</span> <span class="btn-label btn-label-green"> </span> </div> <div class="btn"> <span class="btn-text">Button 2 with large text</span> <span class="btn-label btn-label-red"> </span> </div> <div class="btn"> <span class="btn-text">Btn 3</span> <span class="btn-label btn-label-blue"> </span> </div> </div> 

声明一个maxwidth变量,将其设置为0,然后使用jquery选择器拉动按钮,对于每个按钮,检查其宽度是否大于max的最大值(如果已更新maxwidth变量)。 最后,在浏览完所有按钮后,使用相同的选择器设置所有按钮的宽度。

没有看到您的代码,我无法给您确切的答案,但是有几种方法可以做到这一点。 第一种方法是使用CSS calc函数将按钮左侧的宽度设置为100%减去按钮右侧的宽度:

.button-left {
    width:calc(100% - 40px); /* Change 40px to whatever the width of the right side is */
}

@SumGuy提到的另一种方法是使用jQuery将所有元素的宽度设置为所有按钮的最大宽度。 您可以像这样遍历每个元素来做到这一点:

function equalWidth(element) {
    var maxWidth = 0;
    element.each(function() {
        $(this).removeAttr('style');
        maxWidth = Math.max(maxWidth, $(this).width());
    });
    group.css({ width: maxWidth + 'px' });
}
equalWidth($('.button')); //Change the selector to whatever your button class is.

如果您设置了JSFiddle,那么我可以为您提供适用于您的特定HTML标记的确切答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM