![](/img/trans.png)
[英]How to set all flex elements with the same width which adapts to the longest text?
[英]Setting the width of 2 elements based on longest text
您可以将 min-width 的属性设置为按钮元素。 通过这样做,较小的按钮将与较大的按钮具有相同的宽度。
您可以获得具有较大offsetWidth
的按钮,然后将其应用于另一个按钮的width
样式属性。
const buttons = document.querySelectorAll('button') if (buttons[1].offsetWidth > buttons[0].offsetWidth) { buttons[0].style.width = buttons[1].offsetWidth + 'px'; } else { buttons[1].style.width = buttons[0].offsetWidth + 'px'; }
<button>Hello World!</button> <button>Spectric</button>
如果您有多个按钮,则更可扩展的解决方案:
const buttons = document.querySelectorAll('button') const biggestWidth = [...buttons].reduce((a,b) => a = b.offsetWidth > a? b.offsetWidth + 1: a, 0) buttons.forEach(e => e.style.width = biggestWidth + 'px')
<button>Hello World!</button> <button>Spectric</button>
您可以使用 CSS 网格来做到这一点:
.button-panel { display: inline-grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); column-gap: 10px; }
<div class="button-panel"> <button>A very long button name</button> <button>Ok</button> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.