PAYG Website Design services. Cancel anytime. See Plans

A note about lazy loading images in a multi-column layout

← Blog

In my previous post, I mentioned that I’d added an archive page containing images of old work to my website. To build this, I decided to use CSS columns to create a masonry-style layout without using complex JavaScript or frameworks – just plain old CSS and HTML.

Masonry layouts are where every “brick”, or image in this scenario, fills the gap, so there is no space between it and the one beneath. A good example of this is Pinterest.

Pinterest masonry style layout

CSS columns

CSS columns allow content to arrange itself into columns automatically, so all the content is equally distributed. Adding columns is as simple as inserting the following code into your stylesheet:

.columns {
  column-count: 4;
}
Content flow using CSS column count

It’s a great solution, and it worked well except for one thing. My archive page contains around 90 large images, which totals around a massive 30MB, so it was essential to add some form of lazy loading to the images.

Lazy loading images

Lazy loading is when images load on request, usually as the user scrolls closer to them.

I added the lozad.js script but noticed an excessive amount of content layout shift, making the images jump all over the place. It makes perfect sense – column-count needs to load all the content before calculating how the columns are distributed. So, therefore it makes sense that column-count is ideal for text containing one or two small images.

CSS grid

After more testing and experimenting, I decided to dump column-count and use CSS grid instead to create a four-column layout made up of a single row.

I knew how many images there were in total, and Jekyll can dynamically give us this value, so it was easy to work out how many images there should be in each column.

Content flow using CSS grid

The advantage of this CSS grid method is the images load immediately from the beginning of each column, and each column is independent.

And to make things easier, uploading more images would automatically adjust the images per column.

The result is an archive with a performance score of 90+ on mobile.

Subscribe to my newsletter

Sign up to get my latest blog articles direct to your inbox.

%d bloggers like this: