Css Grid Wrapping
Is It Possible to Make a Css Grid Wrap Without Using Media Queries? in My Case, I Have a Non-Deterministic Number of Items That I Want Placed in a Grid and I...
Is it possible to make a CSS grid wrap without using media queries?
In my case, I have a non-deterministic number of items that I want placed in a grid and I want that grid to wrap. Using Flexbox, I'm unable to reliably space things nicely. I'd like to avoid a bunch of media queries too.
Here's some sample code:
.grid {
display: grid;
grid-gap: 10px;
grid-auto-flow: column;
grid-template-columns: 186px 186px 186px 186px;
}
.grid > * {
background-color: green;
height: 200px;
}
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
And here's a GIF image:
As a side-note, if anyone can tell me how I could avoid specifying the width of all the items like I am with grid-template-columns that would be great. I'd prefer the children to specify their own width.
5 Answers
Use either auto-fill or auto-fit as the first argument of the repeat() notation.
<auto-repeat> variant of the repeat() notation:
repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
Must Read
auto-fill
When
auto-fillis 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 its grid container.
.grid {
display: grid;
grid-gap: 10px;
grid-template-columns: repeat(auto-fill, 186px);
}
.grid>* {
background-color: green;
height: 200px;
}
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
The grid will repeat as many tracks as possible without overflowing its container.
In this case, given the example above (see image), only 5 tracks can fit the grid-container without overflowing. There are only 4 items in our grid, so a fifth one is created as an empty track within the remaining space.
The rest of the remaining space, track #6, ends the explicit grid. This means there was not enough space to place another track.