I'm trying to get some kind of "dynamic" columns depending on the number of items.
The container can have 1 to 4 items. I would like the number of columns to be 3 if there are between 1-3 items and 4 columns if there are 4 items.
This is what I have right now, it works fine if there are 1-3 items, but if there are 4 items then the last one goes to the next row. If I have grid-template-columns: repeat(4, 1fr);
that would work fine for when there are 4 items only.
Is it possible to achieve this with CSS?
Thanks.
.container {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(3, 1fr);
border: 1px solid #c1c1c1;
border-radius: 5px;
padding: 5px;
}
.container > div {
height: 100px;
border: 1px solid #010101;
border-radius: 5px;
}
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
Instead of using explicit columns, which you define using grid-template-columns
, use implicit columns, which the grid creates automatically, as needed.
.container {
display: grid;
grid-gap: 10px;
grid-template-columns: 1fr 1fr 1fr;
grid-auto-columns: 1fr;
grid-auto-rows: 100px;
border: 1px solid #c1c1c1;
border-radius: 5px;
padding: 5px;
}
.container > div {
grid-row: 1; /* keeps all items on the first row */
border: 1px solid #010101;
border-radius: 5px;
}
<div class="container">
<div></div>
</div>
<hr>
<div class="container">
<div></div>
<div></div>
</div>
<hr>
<div class="container">
<div></div>
<div></div>
<div></div>
</div>
<hr>
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
</div>