Flexible CSS grids with dynamic numbers of columns and minimum column widths

Posted by Howard Richardson (comments: 0)

A situation I often encounter is needing a dynamic number of columns in a layout, either as text columns or a grid of items. Usually the items in the grid will have a minimum width requirement so that you can always fit in the basics, but additionally we want the cells to expand out to cover any left-over space when we have divided up things into however many columns our browser width comfortably allows.

For a long time I was experimenting with the grid-auto-columns CSS property, but not getting it to work. This could set fixed-width columns but it wasn't working for dividing the available space fractionally. Then I finally discovered that the key to having this work was use of the repeat function, combined with auto-fit and minmax. Witness:

#container { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); }

#container .child { min-width: 250px; width: 100%; }

With this in place we can see what the grid does is auto-fill as many columns (ie. repeated) and the columns must have a minimum width of 250px, however the maximum is 1fr, meaning that it can expand out to one third or one quarter of the space of however many columns actually fit.

This gives us the holy grail of a stretching grid which responsively adapts to browser width, but with a built in minimum cell size.

You can see this in action on the TLDR website in the blue "Contributions from our friends" area. At full width there are four cells across, but this will drop to three, then two, then one as the browser width shrinks, always keeping the gap between the items the same.

Go back

Add a comment