Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

html - How to limit the amount of columns in larger viewports with CSS Grid and auto-fill/fit?

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:

enter image description here

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:

enter image description here This is my grid layout code.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Documentation

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...