使用Flexbox强制每行最少的项目

时间:2016-11-15 19:30:43

标签: html css css3 flexbox

使用CSS flex,是否可以每行强制使用相同数量的项目?

我可以获取要包装的项目,但不能每行使用相同的数字(Fiddle)。

.container {
    display: flex;
    flex-flow: row wrap;
    position: relative;
}

.container > div {
    padding: 49px;
    flex: 1;
    box-sizing: border-box;
}

这是我想要完成的图表:

enter image description here

2 个答案:

答案 0 :(得分:7)

您可能正在寻找数量查询,根据列表中多少项目更改样式

a list apart article



.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;
&#13;
&#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>

revised fiddle

在上面的示例中,在某个断点处(屏幕宽度为700px,在这种情况下),flex-wrap: wrap已启用,每个弹性项目变为33%宽,每行强制三个项目。

在较小的断点处,flex-basis调整为50%,每行只允许两个项目。