Responsive images in Eleventy

Wednesday, 26 December 2018

There’s nothing quite like a little bit of Christmas eve coding… Adding responsive images to my Eleventy (11ty) build has been on my to-do list for a while… I’ve finally got it working 🎉. And on the basis that I couldn’t find a write up of how other people have done it… this is how I’ve got mine set up.

Generate all the images

May 2020 Update: I changed this step when I migrated away from Gulp. Read about the degulpification

When I switched my site across to 11ty I used Gulp as my build tool. There is a handy image generator which you can point at a folder and it will generate different sized images based on a set of configuration. Imaginatively it is called Gulp Responsive.

You can see the (basic) configuration I’m using over in this Github commit. The summary version is that I generate two smaller versions of the input image which have their image width added into the file name (exampleimage-550.jpg) and all the metadata is stripped out for a small file size. The newly generated images are then exported into the build folder.

From the front matter

My blog posts are all written in Markdown, they have a little bit of custom meta-data stored in Front Matter. One specific bit is the lead image which is output at the top of this blog post.

The front matter stores the original image path, which is fine, however the new image tag requires the modified filename which includes the image width. To get this working I’ve added a universal filter in my 11ty config file which takes in an image path and an image size and returns the correct URL for the image:

Into the Markdown

The images that are included by referencing them in the Markdown is different - you can’t fix that with a filter from 11ty.

11ty (in it’s default) setup uses markdown-it for Markdown parsing. This is good because markdown-it is remarkably extensible, and people have. So, enter markdown-it-responsive which “…overloads original image renderer of markdown-it”.

Having got that installed in the 11ty config file, you can feed in a couple of options and enjoy new image tags in your HTML:

The output can be seen here:
Ooh, responsive images from eleventy

The commits I made over the course of doing this show the progress of this. I also used the time to do a little bit of tidying up around the place:

  1. Generate images
  2. RWD the lead image
  3. Overload markdown-it image tags

Post changelog

Back to all posts