The use of grid-template-columns: repeat(auto-fit, minmax(600px, 1fr))
makes it easy to build a responsive CSS grid. The container will be filled with as many elements fit into a row, without using a media query.
.container {
display: grid;
grid-gap: 5px;
grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
}
.item {
height: 100px;
background: #ccc;
}
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
The problem is that the items are wider than the screen when the screen is smaller than the min-value specified in minmax()
. You can fix this by adding a media query at 400px
, but this only works when you know that there's no content around the container. And that's almost impossible when the container could be placed anywhere.
Is there a way or property to tell the items that they should never be wider than 100%?
Something like: Fill the container with as many 400px items as possible, but ensure that non of them gets wider than 100% of the width of the container.
CodePen Demo
The minmax() CSS function defines a size range greater than or equal to min and less than or equal to max. It is used with CSS Grids.
When you use minmax(0, 1fr) , that's something different than standalone 1fr . In the first case, the track cannot be smaller than the size of the grid item (min size is auto ). In the second case, the track is free to resize to a 0 width/height.
Items are placed by filling each row in turn, adding new rows as necessary. If neither row nor column is provided, row is assumed. Items are placed by filling each column in turn, adding new columns as necessary. "dense" packing algorithm attempts to fill in holes earlier in the grid, if smaller items come up later.
You should change grid-template-columns
to grid-template-columns: repeat(auto-fit, minmax(min-content, 400px))
because minmax
works this way: it tries to apply max value and if fails it applies minimum. But in this you can get blank space in your grid to the right. Demo:
.container {
display: grid;
grid-gap: 5px;
grid-template-columns: repeat(auto-fit, minmax(min-content, 400px));
}
.item {
height: 100px;
background: #ccc;
}
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With