I need to implement a masonry layout. However, for a number of reasons I don't want to use JavaScript to do it.
![A grid of multiple columns of rectangles of varying height.](https://i.stack.imgur.com/Z25DI.png)
Parameters:
- All elements have the same width
- Elements have a height that cannot be calculated server side (an image plus various amounts of text)
- I can live with a fixed number of columns if I have to
The problem with that solution is that elements are ordered in columns:
![Starting from the top leftmost box, they're numbered 1 through 4 straight down, the topmost box in the next column is 5, and so on.](https://i.stack.imgur.com/uRAHy.png)
While I need the elements to be ordered in rows, at least approximately:
![Starting from the top leftmost box, they're numbered 1 through 6 straight across, but because box 5 is the shortest the box underneath it is 7 as it has the appearance of being on a row higher than the next box on the far left.](https://i.stack.imgur.com/d991Y.png)
Approaches I've tried that don't work:
- Making items display: inline-block: wastes vertical space.
- Making items float: left:
Now I could change the server-side rendering and reorder the items by dividing the number of items by the number of columns, but that's complicated, and error-prone (based on how browsers decide to split the item list into columns), so I'd like to avoid it if possible.
Is there some flexbox magic that makes this possible?