The most famous line of code to have come out of CSS grid so far is:
grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr));
Without any media queries, that will set up a grid container that has a flexible number of columns. The columns will stretch a little, until there is enough room for another one, and then a new column is added, and in reverse.
The only weakness here is that first value in minmax()
(the 10rem value above). If the container is narrower than whatever that minimum is, elements in that single column will overflow. Evan Minto shows us the solution with min()
:
grid-template-columns: repeat(auto-fill, minmax(min(10rem, 100%), 1fr));
The browser support isn’t widespread yet, but Evan demonstrates some progressive enhancement techniques to take advantage of now.
There should probably exist a simpler, terser syntax for this common use-case. Maybe in Grid Layout Level 2…
Interesting but I’m pretty sure I’m not alone in feeling that “The only weakness here is that first value in minmax() (the 10rem value above).” is really not the only weakness with this technique.
Rather, it is the unavoidable row-start justification of last row grid items(the last row never centered unless full) – think a gallery. This issue is not illustrated properly in the linked article as the graphic provided conveniently illustrates a perfectly filled last row, but this is frequently not the case. As so: https://codepen.io/mikegleeson/pen/EqmWPm
I’d like something in grid that somehow ‘knows’ the final row should be centered. Considering this is more of a flexbox thing and kind of goes against the grain of what grid is all about, i’m a little skeptical it is do-able with an indeterminate number of rows and items in the final row, but i’m hopeful nonetheless.
Oh, and auto-fit should probably be the pick here, not auto-fill for most use-cases.