This can be done easily CSS grid by using repeat
, auto-fit
, and minmax
.
Essentially what we are doing here is setting the child elements to take up the full width of whatever their "grid container" is, and then we are setting the grid to be auto-fit
and saying that each child will be a minimum of 50px
or a maximum of 1fr
.
Another good approach would be to just use grid-auto-columns
and grid-auto-flow
. Kind of depends on your specific use case for which is the better approach, but be sure to checkout Temani Afif's answer for the other solution.
.grid {
width: 100%;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(50px, 1fr));
}
.grid > div {
background-color: tomato;
height: 50px;
width: 100%;
border: 1px solid black;
}
Example 1:
<div class="grid">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
Example 2:
<div class="grid">
<div></div>
<div></div>
</div>
Example 3:
<div class="grid">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>