To implement grid wrapping in a vertical direction, additional steps are required:
Specify a height
for the grid container to indicate when the grid items should wrap,
Also, specify grid-auto-flow: column
(instead of default grid-auto-flow: row
)
Refer to the demonstration below (where height: 100%
is set for illustration purposes):
body,
html {
height: 100%;
margin: 0;
}
.wrapper {
display: grid;
grid-template-rows: repeat(auto-fill, minmax(140px, 200px));
grid-auto-flow: column; /* added */
height: 100%; /* adjust this*/
}
.wrapper>div:nth-child(odd) {
background-color: red;
}
<div class="wrapper">
<div class="one"> 1 </div>
<div class="one"> 2 </div>
<div class="one"> 3 </div>
<div class="one"> 4 </div>
<div class="one"> 5 </div>
</div>
Reason for specifying a height:
A definite dimension must be provided in that axis when using auto-fill
or auto-fit
:
7.2.3.2. Repeat-to-fill: auto-fill and auto-fit repetitions
When auto-fill is given as the repetition number, if the grid
container has a definite size or max size in the relevant axis, then
the number of repetitions is the largest possible positive integer
that does not cause the grid to overflow the content box of its grid
container (treating each track as its max track sizing function if
that is definite or as its minimum track sizing function otherwise,
and taking gap into account); if any number of repetitions would
overflow, then 1 repetition. Otherwise, if the grid container has a
definite min size in the relevant axis, the number of repetitions is
the smallest possible positive integer that fulfills that minimum
requirement. Otherwise, the specified track list repeats only once.
Simpler approach with Auto-fill in the row direction:
Note that here, a width doesn't need to be specified since display: grid
is a block element and block elements automatically have the width of the viewport. Just utilize
grid-template-columns: repeat(auto-fill, minmax(140px, 200px))
like so:
body,
html {
height: 100%;
margin: 0;
}
.wrapper {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 200px));
/*grid-auto-flow: row; --> default (so not needed) */
}
.wrapper>div:nth-child(odd) {
background-color: red;
}
<div class="wrapper">
<div class="one"> 1 </div>
<div class="one"> 2 </div>
<div class="one"> 3 </div>
<div class="one"> 4 </div>
<div class="one"> 5 </div>
</div>
Importance of grid-auto-flow: column
:
Take a look at excerpts from its definition - this property dictates how grid items flow within a grid container if they are not explicitly placed:
grid-auto-flow
The grid-auto-flow CSS property controls how the auto-placement
algorithm works, specifying exactly how auto-placed items get flowed
into the grid.
The default value of grid-auto-flow
is row
, which is why it needs to be overridden to column
:
row
The auto-placement algorithm places items by filling each row in turn,
adding new rows as necessary. If neither row nor column is provided,
row is assumed.