Adding figures with captions to images in markdown with eleventy

25th July 2021

Problem

Markdown is really flexible for writing text, but it’s support for images is quite simplistic.

Standard images in markdown

![A kitten](http://placekitten.com/400/300)

outputs:

<img src="http://placekitten.com/400/300" alt="A kitten">

e.g.
A kitten

However I want to generate something more useful to readers, i.e. images with nice captions like:

<figure>
    <img src="http://placekitten.com/400/300" alt="A kitten">
    <figcaption>Chesney the Kitten attempts a giant leap<figcaption>
<figure>    

Now you can do this by just including HTML in your markdown, but this gets boring fast, and I wanted a single markdown tag to do this with.

Solution

Use the markdown-it plugin markdown-it-image-figures.

Full plugin docs are here, but if you want to output simple images with alt tags and title like:

<figure>
    <img src="fig.png" alt="This is an alt">
    <figcaption>This is a caption</figcaption>
</figure>

you need the following config alongside your markdown library configuration in your .eleventy.js file:

let markdownIt = require("markdown-it");
let options = {
    // whatever options you have set for the library here
  };
let mdfigcaption = require('markdown-it-image-figures');
let figoptions = {
    figcaption: true
};

const mdLib = markdownIt(options).use(mdfigcaption, figoptions);

module.exports = function (config) {
    //other config here

    config.setLibrary("md", mdLib);
}

N.B. the figcaption option sets the plugin to use a specified image title as the fig caption.

Usage

![A Kitten](http://placekitten.com/400/300 "Chesney the Kitten attempts a giant leap")

outputs the following HTML

<figure>
    <img src="http://placekitten.com/400/300" alt="A kitten">
    <figcaption>Chesney the Kitten attempts a giant leap<figcaption>
<figure>    

which renders with a bit of styling like:

A Kitten

Gotchas to watch out for