05-14-2021

#Tutorial

#CSS

Easily create a masonry grid with the CSS column property.

Font choice:

Recently I set out to create a masonry grid in the easiest way possible. After some experimenting, I was pleasantly surprised that I had a working and responsive masonry grid with less than 15 lines of CSS.

How? By using CSS's column property.

Let me quickly show you how.

First, let's set up our HTML with a grid container and 8 images. For the images, I'll be using an Unsplash link that returns a random image at certain sizes.

<main>
  <section class="photo-grid-container">
    <img class="photo-grid-item" 
         src="https://source.unsplash.com/random/300x300">
    <img class="photo-grid-item" 
         src="https://source.unsplash.com/random/300x314">
    <img class="photo-grid-item" 
         src="https://source.unsplash.com/random/300x500">
    <img class="photo-grid-item" 
         src="https://source.unsplash.com/random/300x313">
    <img class="photo-grid-item" 
         src="https://source.unsplash.com/random/300x612">
    <img class="photo-grid-item" 
         src="https://source.unsplash.com/random/300x401">
    <img class="photo-grid-item" 
         src="https://source.unsplash.com/random/300x312">
    <img class="photo-grid-item" 
         src="https://source.unsplash.com/random/300x611">
  </section>
</main>

This should output a column of 8 images stacked on top of each other. Now we'll add the CSS below and watch the magic happen. Column count, width, and gap are going to do the majority of the work for us.

.photo-grid-container {
  column-count: 5;
  column-width: 200px;
  column-gap: 10px;
  width: 100%;
/*   Remove max-width for full-screen grid */
  max-width: 1600px;
  margin: auto;
}
.photo-grid-item {
  margin: 0 auto 5px;
  width: 100%;
}

And there you have it! 🎉

A masonry photo grid.

View this example on CodePen.

Now you have a quick and stress-free method of creating a responsive masonry grid with under 15 lines of CSS. I hope you found it helpful and thanks for taking the time to read this post!

Until next time.

-Kyle Shook (elyktrix)