To wrap grid in vertical direction you have to do a bit more:
specify a height
for the grid container so that the grid items know when to wrap,
also specify grid-auto-flow: column
(overriding default grid-auto-flow: row
)
See demo below (have set height: 100%
for illustration):
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>
Why specify a height?
Because auto-fill
or auto-fit
requires a definite dimension in that axis:
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.
Auto-fill in row direction is simpler
Note that here, you don't need to specify a width as display: grid
is a block element and block elements have the width of the viewport. You can just use grid-template-columns: repeat(auto-fill, minmax(140px, 200px))
here:
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>
Why grid-auto-flow: column
?
See the relevant excerpts from its definition - this property controls how grid items flow in 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 you need to override it 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.