AaronRutley.com

Flexible & Responsive Gallery with Sass

Posted in Web Development on the 18th of March 2015 by @aaronrutley

When I was designing my Travel Blog a few months ago, I wanted a gallery layout that was “Flexible”. I wanted the layout of each gallery to adapt based on the number of images it contained, ensuring that a gallery of images would always fill the screen & avoid awkward “leftover” images.

The gallery also needed to be responsive to ensure it worked well on a range of devices.

For example, a traditional photo gallery on a desktop screen could have 3 columns and as many rows as required. Therefore if you have a gallery of 7 images, on a desktop sized screen this would result in 3 rows of images, the first two rows would contain 3 images each and the third row would have only 1 “leftover” image.

Traditional Gallery

This is an example of a traditional gallery on a desktop screen

To avoid this 1 “leftovoer” image on desktop sized screens, I decided it would be best in this case to have just two rows of images, one row would contain 3 images and the other would contain 4 images.

Flexible Gallery

This is how I decided a gallery that contained 7 images should appear on a desktop sized screen.

I realised I could easily solve this with a little HTML & CSS

All I needed to do was add a couple of classes, I added class on the container that has a count of all images in the gallery, for example “gallery-7-up”. Then I added a class to each image within that container has a class with it’s number and gallery, for example “image-1-of-7” (both of these classes are generated via some simple php counters so there’s no manual work or settings involved). I also realise this could be solved with JS or Flexbox ; )

Here's an example of the HTML for a gallery of 7 items

I ended up coding up a custom Sass/Scss mixin to gerenate the responsive CSS with a mobile first approach. Thanks to the helper classes I could easily target each image at each breakpoint which lets me manipulate the gallery as needed !

Here's an example of the Sass for a gallery of 7 items
Here's the whole Sass / Scss partial

A bonus side effect is the galleries look a little more interesting as the image sizes vary throughout from post to post, see it in action here : rutsandbel.com ; )

Share this post

Menu