[英]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.