I am facing a challenge with my flexbox container where I want it to display elements in multiple rows when there are more than a set number of items. Below is my current approach:
.container {
display: flex;
width: 400px;
background: black;
padding: 6px;
margin: 10px;
flex-wrap: wrap;
}
.box {
flex: 1 1 0;
height: 32px;
flex-grow: 1;
min-width: 15%;
border: solid 1px black;
}
.box:nth-child(even) {
background: blue;
}
.box:nth-child(odd) {
background: red;
}
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
Visit this link for the full code snippet.
The issue I'm encountering is that the items in the last row stretch to fill the row unevenly.
My goal is to evenly distribute the elements among rows so that each element is as close to the same size as possible.
For instance, if there are a maximum of 6 elements per row and there are 8 elements total, I want 4 elements on each row instead of 6 on the first row and 2 on the second.
Is achieving this distribution possible using flexbox or any other method?