Fully responsive CSS grid elements and minmax auto-installation

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

+5
source share
2 answers

Fill the container with as many 400px elements as possible, but make sure they do not have a width greater than 100% of the width of the container.

For this you can use the "max-content" property, in your example it will be:

 .unresponsive { grid-template-columns: repeat(auto-fit, minmax(400px, auto)); grid-auto-columns: max-content; } 
0
source

You should change grid-template-columns to grid-template-columns: repeat(auto-fit, minmax(min-content, 400px)) because minmax works like this: it tries to apply the maximum value, and if it doesn't work, It applies a minimum. But in this you can get the empty space in your grid on the right. Demo video:

 .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> 
0
source

Source: https://habr.com/ru/post/1274331/


All Articles