patstuart patstuart - 24 days ago 7
CSS Question

Force minimum items per row with Flexbox

Using CSS flex, is it possible to force an equal number of items per row?

I am able to get the items to wrap, but not to have the same number per row (Fiddle).

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

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


Here is a diagram of what I'm trying to accomplish:

enter image description here

Answer

May be you are looking for quantity queries, where you change the style depending on how many items there are on a list

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>