有没有一种方法可以根据具体的子金额确定 css/html 的布局?
请参阅下面的布局示例。
我试图让它与第 nth-child 一起工作,但我可能做错了..
https://codepen.io/brycesnyder/pen/EvBzWq
但我不确定是否有办法让所有元素跨越 50% 的宽度,如果超过 1 个,则以下应该堆叠。
/* three items */
li:first-child:nth-last-child(3):not(:first-child),
li:first-child:nth-last-child(3) ~ li {
background: green;
}
编辑:我知道这可以通过像这样的标准元素实现:https://codepen.io/brycesnyder/pen/GvbbyY我希望能够只使用 UL > LI
最佳答案
所以...它不完全是“基于 child 的数量”,但您可以通过将 flex 方向更改为列,将宽度设置为 50%,并让第一个元素具有柔性; 0 0 100%。您还需要将 1 个子列表 (:first-child:nth-last-child(1)) 的特殊情况设置为宽度 100%。
关键的 css 最终看起来像这样:
ul {
padding:10px 1px;
display: flex;
flex-direction: column;
flex-wrap: wrap;
height: 200px;
list-style-type: none;
}
li {
outline:1px solid gray;
text-align:center;
width: 50%;
margin: 0;
padding: 0;
flex: 1 1 auto;
}
li:first-child {
height: 100%;
flex: 0 0 100%;
}
/* one item */
li:first-child:nth-last-child(1) {
width: 100%;
}
这是我从你的 fork 出来的代码笔:
关于html - 根据 flex 子项数确定布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46121366/