Markdown header links with markdown-it
Date: 2022-12-05 | markdown | markdown-it | html
Linking to a header
Most web browsers allow for linking to specific headers on a page provided a few things are true:
- Header: an
- Url: ends with
This url will prompt the browser to jump to the header on the page with the matching
id attribute, if it exists.
Header links with
markdown-it is a popular npm library for converting markdown files to renderable HTML. This is a common method for building content-focused web pages and ensuring the data and views are decoupled.
markdown-it does not create
id attributes on headers by default making it impossible to link to headers rendered via this method.
markdown-it header links with
To solve this, we can use mardown-it-anchor. This library is a
markdown-it plugin that specifically allows us to add
id attributes to the rendered HTML.
Assuming you already have
markdown-it working in your site, we can simply plug
markdown-it-anchor into the render pipeline:
import markdownIt from "markdown-it" import markdownItAnchor from "markdown-it-anchor" // ... const md = markdownIt() .use(markdownItAnchor) const mdHtml = md.render(MARKDOWN)
This should enable you to link directly to header sections.
This is the same technique I'm using to render header links for my markdown files here on the site.
If you're interested in learning more about how I build websites, check out Up and Running with CloudSeed (F# / SvelteKit boilerplate)