簡體   English   中英

根據最長文本設置2個元素的寬度

[英]Setting the width of 2 elements based on longest text

我正在嘗試根據較大元素的文本確定使 2 個元素大小相同的最佳方法。

德語文本 - 相同大小

法語文本示例 2 種不同大小

基本上采用 2 個文本項“ouverture de session”和“xyz”(用於簡短的單詞示例),以便兩個按鈕大小相同,並且足夠大以處理 2 個文本輸入中較大的一個。

這可以通過 Javascript、Angular 等來完成。

您可以將 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM