CSS Grid to have minimum number of columns possible with auto flow after wrapping

旧巷老猫 提交于 2020-04-17 16:56:57

问题


Is it possible to have a CSS grid with auto flow that minimises the number of columns after wrapping? How?

I have a grid with 6 items with auto-placement. Once not all 6 of them fit in one row, I'd like to have 3 columns and 2 rows, instead of 5 columns and 1 row, with only one element on the second one.

I'd like to avoid media queries, if possible.


A visual representation of what I'd like to do:

1) If all 6 items fit in one row, show them in one row.

| OOO OOO OOO OOO OOO OOO | 
| O1O O2O O3O O4O O5O O6O |
| OOO OOO OOO OOO OOO OOO |

2) If fewer than 6 elements fit in one row, show them in 2 rows with 3 items each.

| OOO OOO OOO         | 
| O1O O2O O3O         | 
| OOO OOO OOO         | 
|                     | 
| OOO OOO OOO         | 
| O4O O5O O6O         | 
| OOO OOO OOO         | 

3) If fewer than 3 elements fit in one row, show them in 3 rows with 2 items each.

| OOO OOO   | 
| O1O O2O   | 
| OOO OOO   | 
|           | 
| OOO OOO   | 
| O3O O4O   | 
| OOO OOO   | 
|           | 
| OOO OOO   | 
| O5O O6O   | 
| OOO OOO   | 

Here's what I got so far. Reduce width until the last column wraps, at that point I'd like to have 3 columns with three items each instead of one with 5 and another with 1.

.grid {
  padding: 10px;
  border: 2px solid #444;

  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  gap: 10px;
  justify-content: space-evenly;
}

.item {
  height: 50px;
  background: #5a5a;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2em;
}
<div class="grid">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
</div>

回答1:


Edit: Please note that I wrote the answer before the OP added their code to the question. However, I still think that @media queries are needed to solve this problem, independent of the method in which the div elements are displayed.


Original Answer:

I've made a demonstration below using a br tag and @media queries.

Run the snippet and then press 'Full Page' to test it:

.grid-box {
  display: inline-block;
  width: 200px;
  height: 150px;
  background-color: blue;
  margin: 2px;
}

.row3 {
  display: none;
}

@media (max-width: 1260px) {
  .row3 {
    display: block;
  }
}

@media (max-width: 636px) {
  .row3 {
    display: none;
  }
}
<div class="grid-box"></div>
<div class="grid-box"></div>
<div class="grid-box"></div>
<br class="row3">
<div class="grid-box"></div>
<div class="grid-box"></div>
<div class="grid-box"></div>


来源:https://stackoverflow.com/questions/60400211/css-grid-to-have-minimum-number-of-columns-possible-with-auto-flow-after-wrappin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!