CSS masonry with flexbox, :nth-child(), and order

Tobias Ahlin:

On the surface it seems fairly easy to create a masonry layout with flexbox; all you need to do is set flex-flow to column wrap and voilà, you have a masonry layout. Sort of. The problem with this approach is that it produces a grid with a seemingly shuffled and obscure order.

Flexbox has no easy way of rendering items with a column layout while using a row order, but we can build a masonry layout with CSS only — no JavaScript needed — by using :nth-child() and the order property.

Beware though: this technique requires you to set a fixed height on the wrapper, which is not always possible 😕

CSS masonry with flexbox, :nth-child(), and order

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.