Creating a dynamic masonry layout?

I’ve got a section on the site I’m building where I would like to have a masonry-based grid. However, the section will be dynamic (using calls from the database within my Wordpress project) and so I would like the layout to adjust according to the number of items added, both horizontally and vertically. There will likely be a maximum of 10-15 items in the grid and a minimum of 5 (I’ll set a maximum via the database call).

I’ve heard that CSS Grid’s “masonry” grid-template-columns is on the way, but is there a good method I could follow in the meantime with CSS Grid or Flexbox?


Does this article help? I’m not sure about the grid adjusting horizontally. I’m not sure how that would work. Obviously you will be using PHP to handle the dynamic side of it.

1 Like

Check out Gandalf’s link.

Based on what I know of Masonry, the vertical columns do not change in width (“both horizontally and vertically”), just vertically.

1 Like

Thank you both. Apologies I should have been clearer - I’m looking for a vertical masonry solution but with a clean edge on the top and bottom. I’ve figured out that I will probably adjust the column numbers according to the screen width rather than making it fully dynamic.

After doing some searching I’ve found the following article from CSS Tricks which may help?

Css columns can do quite a reasonable masonry type layout but won’t give a clean bottom edge.

1 Like

Thanks Paul, I’ll bear that in mind! :slight_smile:

This Pen from the article above seems to work - can you see any drawbacks?

The main drawback is that the demo doesn’t include any real content so we have no way of knowing what it will look like with real content in there. As it stands its just stretched backgrounds.

I tried inserting some dummy text and it broke the whole thing. I think you would need to play around with the demo a bit first and add some real looking content and see what it looks like and how easy it is to work with.

The main problem is that html order has been changed which for accessibility reasons is a big drawback. However the masonry script probably has the same drawbacks.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.