How to Make Css Masonry Grid that fill gaps

October 13, 2023


Css Masonry Grid that fills gaps


I recently had to make a masonry grid. I wanted it to generate new images & align the images at the bottom of the grid so that they would fill in any holes that were empty. Something like the pinterest grid layout. I wanted to do this with just css, no javascript. To my surprise, it wasn't as hard as I thought it was going to be.

The width of the grid will be 1024px, the height will go as long as needed. There will be 4 columns each with a width of 256px. The rows will auto-fit & they will have a height of 256px. I will set grid-auto-flow to dense so that when another image is generated it will fit into any holes that it can, if it can't it will start a new row if needed at the end of the grid.

The code for the grid


Grid Settings for the Images


I made 1 image at the size of 256px by 256px. I made the grid-column setting to be (span 1), which means it will span 1 column & also made the grid-row setting to be the same so that it will span 1 row. I made the 2nd image 512px by 512px. I made it the grid-column setting to be (span 2), so that it spans 2 columns. I also did the same with the grid-row setting (span 2).

The code for each of the image elements

In this version instead of using images, I used color boxes that can be generated through a form. These boxes can also be deleted with a click of a button. Each time you generate a new box, if it can fit into an empty hole it will, if it can't it will put itself at the end of the grid. Even when you delete a box that is 512px by 512px the holes will be filled with whatever boxes that fits.

The project can be found here.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.