Using grid-template-columns: repeat(auto-fit, minmax(600px, 1fr)) simplifies building a flexible CSS grid. The container will be filled with so many elements that fit into the string, 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 elements are wider than the screen when the screen is less than the minimum value specified in minmax() . You can fix this by adding a media request at 400px , but this only works when you know that there is no content around the container. And it is almost impossible when the container can be placed anywhere.
Is there a way or property to tell the elements that they should never be more than 100%?
Something like: Fill the container with as many 400px elements as possible, but make sure that they do not exceed 100% of the width of the container.
CodePen Demo
source share