我想在第一行显示4个项目,但只有3个在第二行,然后4个在第三行和3个在第四行,以此类推。。。
我已经通过nth-child
实现了这一点,但是代码太多,不灵活,可扩展。
可以用flex吗?还是网格?
* {
box-sizing: border-box;
}
.grid-wrapper {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.grid-wrapper .grid-item {
width: 25%;
text-align: center;
padding: 5px;
}
p {
background: #ddd;
padding: 15px;
}
<div class="grid-wrapper">
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
</div>
最佳答案
您只需考虑以下一条规则:
/*7 = 4 (1st row) + 3 (2nd row) and 5 = 1st element in 2nd row (4 + 1)*/
.grid-wrapper .grid-item:nth-child(7n + 5) {
width: calc(100%/3);
flex-grow:0;
}
诀窍是使一个元素变大以触发包装,然后依赖于
flex-grow
来填充空间。完整代码
* {
box-sizing: border-box;
}
.grid-wrapper {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.grid-wrapper .grid-item {
width: 25%;
text-align: center;
padding: 5px;
flex-grow: 1;
}
.grid-wrapper .grid-item:nth-child(7n + 5) {
width: calc(100%/3);
flex-grow:0;
}
p {
background: #ddd;
padding: 15px;
}
<div class="grid-wrapper">
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div>
<div class="grid-item">
<p>Grid Item</p>
</div><div class="grid-item">
<p>Grid Item</p>
</div>
</div>
关于html - 使用flexbox连续控制元素数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55868057/