[英]Make CSS grid or flex item equal size with stretched separator between
我嘗試構建一個動態工具欄,其中:
預期的 output(給定BBB
最寬的工具):
—————————————————————————————————————————————————————
| A |BBB| CC| SEPARATOR | D |
—————————————————————————————————————————————————————
我嘗試使用flex
方法,我無法組合所有規則:
—————————————————————————————————————————————————————
|A|BBB|CC| SEPARATOR |D|
—————————————————————————————————————————————————————
nav { display: flex; background: #e8e8e8; width: 100%; }.item { flex: 1; text-align: center; }.separator { width: 100%; background: #d3d3d3; }
<nav> <div class="item">A</div> <div class="item">BBB</div> <div class="item">CC</div> <div class="separator"></div> <div class="item">D</div> </nav>
—————————————————————————————————————————————————————
| A | BBB | CC | SEPARATOR | D |
—————————————————————————————————————————————————————
nav { display: flex; background: #e8e8e8; width: 100%; }.item { flex: 1; text-align: center; }.separator { flex: 1; background: #d3d3d3; }
<nav> <div class="item">A</div> <div class="item">BBB</div> <div class="item">CC</div> <div class="separator"></div> <div class="item">D</div> </nav>
使用grid
系統,如果不指定我想避免的grid-template-columns
,我將無法獲得分隔符。 我需要一些動態的東西。
nav { display: grid; grid-auto-columns: minmax(0, 1fr); grid-auto-flow: column; background: #e8e8e8; width: 100%; }.item { text-align: center; }.separator { justify-self: stretch; background: #d3d3d3; }
<nav> <div class="item">A</div> <div class="item">BBB</div> <div class="item">CC</div> <div class="separator"></div> <div class="item">D</div> </nav>
如果沒有 CSS 解決方案,我對 JavaScript 解決方案持開放態度。 謝謝您的幫助。
通過 javascript,您可以遍歷.item 並查找最寬的,然后更新自定義 css 屬性。
通過 js 和 flex 的可能示例
var bigW = "0"; for (let e of document.querySelectorAll("nav.item")) { elW = e.offsetWidth; if (elW > bigW) { bigW = elW; } document.documentElement.style.setProperty("--myW", bigW + 1 + "px"); }
nav { display: flex; background: #e8e8e8; width: 100%; }.item { min-width: var(--myW, 3em); text-align: center; }.separator { flex: 1; background: #d3d3d3; } nav div+div { border-left: solid; }
<nav> <div class="item">A</div> <div class="item">BBB</div> <div class="item">CC</div> <div class="separator"></div> <div class="item">D</div> </nav>
從下面的評論中編輯
var bigW = "0"; for (let e of document.querySelectorAll("nav > div")) { elW = e.offsetWidth; if (elW < 7) {// includes partially possible border and padding, mind it e.style.flexGrow = 1; } else if (elW > bigW) { bigW = elW; } } document.documentElement.style.setProperty("--myW", bigW + 1 + "px");
nav { display: flex; background: #e8e8e8; }.item { min-width: var(--myW, 0); text-align: center; border: solid 1px; }.separator { background: #d3d3d3; }
<nav> <div class="item">A</div> <div class="item">BBBBBBBB</div> <!--<div class="separator"></div>--> <div class="item">CC</div> <div class="separator"></div> <div class="item">D</div> </nav>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.