[英]How assign the width of the longest element to other elements
如果仅在CSS中寻找解决方案,则有一种方法可以将display
属性用作table
, table-row
和table-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.