Is it possible to create a CSS grid layout with automatic flow that adjusts the number of columns after wrapping? How can this be achieved?
Currently, I have a grid containing 6 items with auto-placement. When all 6 items do not fit in a single row, I would like the grid to display them in 3 columns and 2 rows instead of 5 columns and 1 row where the second row only has one element.
I am looking for a solution that does not involve the use of media queries.
A visual example of what I want to achieve:
1) If all 6 items fit in one row, they should be displayed in a single row as follows:
| 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, they should be represented 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, they should be arranged 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 is the progress I've made so far: I adjust the width until the last column wraps, at which point I'd like to switch to a layout with 3 columns, each containing three items, rather than continuing with 5 columns and then having one item on its own.
.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>