Adding Custom Anchors to Headings in Markdown — Eleventy

Anchors are nothing but id attributes applied to an element to link to it using href attribute internally on the same page.

By default, 11ty uses markdown-it library to parse markdown. But, it seems that by default, markdown-it doesn’t support syntax for applying an id to a header element.

The syntax for applying a custom id to a header element in markdown is as follows:

To make that syntax work, you need to create your own instance of markdown-it library and add two plugins, markdown-it-anchors and markdown-it-attrs.

The markdown-it-anchors plugin will apply a default id depending on the heading text automatically to every header element in our markup.

The markdown-it-attrs plugin will replace the default id with the custom id you specify.

Applying Custom Anchors

Install the required dependencies:

Require them inside `.eleventy.js` file,

Create an instance of the markdown-it library inside the module.exports function.

You can also add some options such as:

Now, if you do something like:

In this case, head1 will be the id of this header element. You can link to this element by using #head1 as the href value. That’s how you can add custom anchors to heading elements.

Applying Default Anchors

If you don’t want a custom id and just want to keep the default id that’s being applied to the element by the markdown-it-anchors plugin, then remove the markdown-it-attrs plugin and you will get a default anchor applied to the element.

That’s all for now. Signing Off.

This post was originally published in Syntackle.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store