Peter Hinchley

Learning in Public

✪ Creating a Responsive Full Width Image Gallery with HTML and CSS using Flex

Today I started work on the development of an image gallery using HTML and CSS. The gallery was based on a grid of thumbnails. Each image was square, and all were of the same size: 240px x 240px.

These were the requirements:

  1. The grid was to be "full width". In other words, the thumbnails must expand/contract/wrap to ensure whitespace never appears at the sides of the grid when the browser window is resized.
  2. The thumbnails are never to grow beyond their original size.
  3. The thumbnails are never to shrink beyond 50% of their original size.
  4. The aspect ratio of the thumbnails must be retained.
  5. All thumbnails are to be shown at the same size.
  6. The last row is to be left aligned.
  7. No JavaScript.

I experimented with a few options that made use of flex-grow to dynamically scale the thumbnails to yield a "full width" experience, but in each case, I couldn't find a non-hacky way of preventing the images within a partial last row from growing too large. Here is a CodePen demonstrating the issue.

So instead of using flex-grow I switched to a combination of flex-shrink and media queries; the latter being used to effectively control the number of columns within the grid based on 240px increments. Here is a CodePen with a working demonstration.

And here is the same pen but with the CSS written using SCSS.