TL;DR: Check out the Codepen. Also note that after publishing, I found that there are much nicer, stable solutions that preserve perfect aspect ratio if needed (see react-photo-gallery & Justified Gallery).

I was on a hunt for a special type of masonry layout for an image gallery today. It needed to fulfill the following requirements:

  1. Row based (every item in the row has the same height)
  2. Gapless (no white leftover areas)
  3. Works in tandem with object-fit: cover on the images
  4. Optimizes for minimal crop on each image
  5. Supports specific row heights
What it should look like.

Much to my surprise and dismay, I couldn’t find anything that would fit the bill…which was surprising to me, so please correct me if this has been done a thousand times before and I just didn’t look hard enough :) (update: didn’t take long to be corrected! react-photo-gallery & Justified Gallery look awesome, thanks for the tip Shane & Swipe Pages).

Anywho, I don’t often get to code these days, but this was a fun problem. The first three requirements are not very difficult, but the forth requires me to try a multitude of combinations per row (3 cols? 4 cols? 5 cols? 50px height? 100px height? and so on), then finding the variant with the least delta between viewport (container) width and summarized row width, and then dividing the ‘leftover’ whitespace into equal parts as ‘gifts’ to each image in the row (which then adds a crop factor via object fit).

Update: react-photo-gallery and Justified Gallery work similarly. One difference is that I thought it’d be nice to be able to choose your own row heights (e.g. 50, 100, 200) if you don’t mind a little crop, which possibly makes for a slightly more ‘stable’ look.

Give it a try (tap or drag the images to see the the ‘crop factor’ for each):

Reply with a tweet or leave a Webmention. Both will appear here.