我尝试构建一个动态工具栏,其中:
预期的输出(考虑到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>