Different size box fill in the gap theme effect with Flexbox

I am trying to do a fill in the gap theme affect with HTML and CSS with flexbox. If there is any available space, the boxes will try to take up the space efficiently as possible, leaving no gaps except margins. It seems like a new modern theme; here is a diagram I made to show you what I mean:

Not my best drawing, but each of those gray box is a child in a parent container. The boxes are different sizes, let fit together to take up as much space as possible with an equal margin (my diagram isn’t perfect). Generally, the whole thing is going downwards with a couple of boxes wide and as much space as I need vertically.

How can I do this with flexbox? Hopefully this made sense…

The term you’re looking for is “Masonry Layout”.

1 Like

Flexbox can only align items along 1 axis, so if you insist on using flexbox to make that layout you’ll have to add a bunch of extra container elements. For example, one subcontainer div to house elements on the left side, and one to house those on the right side, and then more sub-containers in the left one. Here’s an example, but I should’ve added another sub-container to the left one so that margins etc align:


1 Like

Thanks. I will not be using the sub container method, but now i know I will go off and do some more research with this information and see if their is a solution. A in between part between sub containers and masonry layout.

Thank you both for your help!