使用CSS flex,是否可以每行强制使用相同数量的项目?
我可以获取要包装的项目,但不能每行使用相同的数字(Fiddle)。
.container {
display: flex;
flex-flow: row wrap;
position: relative;
}
.container > div {
padding: 49px;
flex: 1;
box-sizing: border-box;
}
这是我想要完成的图表:
答案 0 :(得分:7)
您可能正在寻找数量查询,根据列表中多少项目更改样式
.container {
display: flex;
flex-flow: row wrap;
border: solid 1px green;
}
.container > div {
flex: 1 0;
background-color: lightgreen;
height: 30px;
margin: 5px;
}
.item:first-child:nth-last-child(3),
.item:first-child:nth-last-child(3) ~ .item {
flex-basis: 30%;
}
.item:first-child:nth-last-child(4),
.item:first-child:nth-last-child(4) ~ .item {
flex-basis: 40%;
}

<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
&#13;
答案 1 :(得分:4)
您可以使用flex-wrap
来控制包装和媒体查询,以调整弹性项目的大小:
.container {
display: flex;
flex-flow: row nowrap; /* disable browser-controlled wrapping */
}
.container > div {
padding: 49px 0;
text-align: center;
flex: 1;
box-sizing: border-box;
}
input[type=button] {
background: red;
}
@media ( max-width: 700px) {
.container { flex-wrap: wrap; }
.container > div { flex-basis: 33.33%; }
}
@media ( max-width: 400px) {
.container > div { flex-basis: 50%; }
}
<div class="container">
<div><input type="button" value="Button 1"></div>
<div><input type="button" value="Button 2"></div>
<div><input type="button" value="Button 3"></div>
<div><input type="button" value="Button 4"></div>
<div><input type="button" value="Button 5"></div>
<div><input type="button" value="Button 6"></div>
</div>
在上面的示例中,在某个断点处(屏幕宽度为700px,在这种情况下),flex-wrap: wrap
已启用,每个弹性项目变为33%宽,每行强制三个项目。
在较小的断点处,flex-basis
调整为50%
,每行只允许两个项目。