I'm starting to work with CSS Grid, I've been reading about the properties to help with responsiveness; so I'm trying to build a small grid with 6 elements; my intention is for them to show as 2 rows on larger devices like this:
And also to show them all stacked on smaller devices,so everything is good regarding the smaller devices, I'm using auto-fill so it stays responsive, however if I the view the page on a laptop screen or desktop it is able to fill one more column and ends up looking like this:
display: grid;
grid-template-columns: repeat(auto-fill, 260px);
justify-content: center;
row-gap: 18px;
column-gap: 18px;
Is there a way to keep the responsive behavior but setting a max number of columns as well? Any help is appreciated; If it can only be done with media-queries that's fine, but I'm first trying to look for ways to do it without using those. Also, I kinda made it work as intended by setting a horizontal padding to the whole grid container to compensate for the size of the additional column; but again, if there's a better way I'm all ears. Thank you!
Working Example https://codepen.io/IvanS95/pen/NEYdxb
Use this syntax:
grid-template-columns: 260px 260px 260px;
Or
grid-template-columns: repeat(3,260px);
Instead of this:
grid-template-columns: repeat(auto-fill, 260px);
Use media queries to set less columns on smaller screens.
Also if the row and column gap is the same you can use grid-gap.
.grid-container{
display: grid;
grid-template-columns: 260px 260px 260px;
grid-gap: 18px;
background-color: #fff;
color: #444;
justify-content: center;
}
.card {
border: 1px solid #000;
width: 260px;
height: 260px;
}
<div class="container">
<div class="grid-container">
<div class="grid-item">
<div class="card"></div>
</div>
<div class="grid-item">
<div class="card"></div>
</div>
<div class="grid-item">
<div class="card"></div>
</div>
<div class="grid-item">
<div class="card"></div>
</div>
<div class="grid-item">
<div class="card"></div>
</div>
<div class="grid-item">
<div class="card"></div>
</div>
</div>
</div>
Add this code to your CSS:
grid-template-columns: auto auto auto;
来源:https://stackoverflow.com/questions/53434024/how-to-limit-the-amount-of-columns-in-larger-viewports-with-css-grid-and-auto-fi

