DEV Community 👩‍💻👨‍💻

Cover image for CSS Easy Masonry Grid
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

CSS Easy Masonry Grid

Today we are going to look into making a straightforward CSS Masonry grid.
For those who don't know what a Masonry grid is, it's a grid where items that are not equal in size match up.
Back in the days, this was quite hard to achieve, and you had to use some bloated JavaScript framework to accomplish this.
Nowadays, we can make it with very little use of CSS.

HTML Structure

<div class="masonry">
  <img
    src="https://images.unsplash.com/photo-1551675705-72513c2722a2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60"
  />
  ... More images
</div>
Enter fullscreen mode Exit fullscreen mode

As you can see, I tried to keep it as simple as possible by only using one masonry container and adding several images in it.

CSS Masonry

.masonry {
  column-count: 3;
  column-gap: 0;
}
.masonry img {
  display: block;
  max-width: 100%;
}
Enter fullscreen mode Exit fullscreen mode

Yes, that's all! We define a column-count which will make 3 columns and I added a gap of 0 to make it look better.
Then each image we give a max-width so it doesn't break out.

View and play with this demo on Codepen.

See the Pen CSS Easy Masonry Grid by Chris Bongers (@rebelchris) on CodePen.

Browser Support

The browser support for column-count is actually impressive!
IE10+, and all major browsers.

View on caniuse

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (2)

Collapse
 
b3nnu3 profile image
Benjamin Schnoor

Moin, I think this will destroy the initial order of the images. Isn't it?
Before it was from left -> right. But now its top -> down for each column.

Collapse
 
dailydevtips1 profile image
Chris Bongers Author

Hi Benjamin, Yes in this example it will destroy the order it is more to demonstrate the absolute basis of it.
We can, of course, make them horizontal ordered with a bit more flexbox queries.

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.