Currently, the use of
grid-template-columns: repeat(auto-fit, minmax(25rem, 1fr));
Results in this behavior: If there are more items than can fit in a row (based on the minimum), new rows are created. If there are fewer items than the row could accommodate, the items expand to fill the remaining space.
However, what if you don't want them to fill the space but instead have a maximum size? While setting the item's max-width partially addresses the issue, it also disperses the items across the container. Instead of filling the space or being spread out across the container, I would prefer the items to have a maximum size and sit next to each other when the grid is wider than the total number of items.
Is there a way to achieve this desired behavior?
Snippet demonstrating a grid larger than the total number of items:
html {
font-size: 62.5%;
}
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(25rem, 1fr));
grid-template-rows: repeat(2, 20rem);
grid-gap: 1rem;
border: 1px solid lightgrey;
padding: 1rem;
}
.item {
background: lightblue;
// max-width: 35rem;
}
<div class="container">
<div class="item item-1">1</div>
<div class="item item-2">2</div>
<div class="item item-3">3</div>
<div class="item item-4">4</div>
</div>