csscss-grid

How do I fill columns first then fill rows responsively with css grids?


I have a dynamic list of items which I would like to display. I would like them to fill the first row of a grid adding columns as needed until the row fits the container. Next, it should fill the second row, then fill the third row, etc. I don't care about the order but it would be nice to have the items displayed from top to bottom, column by column like so:

1  4
2  5
3  6

The parent container doesn't have a fixed height. Here's what it should look like: enter image description here

This works, but I have to specify the number of rows explicitly. Is there a way to do this without explicitly specifying rows / columns?

Codepen

Here's the order I want the grid to fill up in:

First:

1 2 3 4 |

Next (no more room on first row):

1 3 5 7 |
2 4 6 8 |

Next (no more room on second row):

1 4 7 10 |
2 5 8 11 |
3 6 9 12 |

Solution

  • I don't believe your desired layout is possible with CSS Grid alone.

    As I see it, you want grid-auto-flow: row working until the columns fill the first row. At that point, you want to switch to grid-auto-flow: column.

    Even if that adjustment could be scripted in, I'm not sure it would work without setting explicit heights or rows on the container.