Reputation: 1343
Currently, using grid-template-columns: repeat(auto-fit, minmax(25rem, 1fr));
Behaves as follows: If there are more items than fit in a row (based off the min), then new rows are created. If there are fewer items than the row could take then the items expand to fill the remaining space.
But what if you don't want them to fill the space, but have a maximum size? Setting the item's max-width sort of solves the problem, but then spreads the items across the container. Instead of filling the space, or being spaced across the container, I'd like the items to have a max size and sit next to each other if the grid is wider than the total number of items.
Is this behaviour possible?
Snippet showing grid > total 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>
Upvotes: 0
Views: 222
Reputation: 691
You should use auto-fill
instead of auto-fit
. The difference is that auto-fill
fills the row with as many columns as it can fit and auto-fit
expands the columns to fit them in the available space.
I created this jsfiddle with a solution.
grid-template-columns: repeat(auto-fill, minmax(25rem, 1fr));
Upvotes: 1