Skip to content
HiDeoo

Add links to Starlight headings

Published on - Reading time

Using a rehype plugin, you can add links to Starlight headings to make it easier to share a link to a specific section of your documentation.

Prerequisites

You will need to have an existing Starlight website.

Add the plugin

First, install the rehype-autolink-headings plugin and also the @astrojs/markdown-remark package:

npm install rehype-autolink-headings @astrojs/markdown-remark

Configure the plugin

Import the plugins in your astro.config.mjs file to add them to the markdown.rehypePlugins array:

astro.config.mjs
import { defineConfig } from 'astro/config'
import starlight from '@astrojs/starlight'
import { rehypeHeadingIds } from '@astrojs/markdown-remark'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
export default defineConfig({
integrations: [starlight({ title: 'My Docs' })],
markdown: {
rehypePlugins: [rehypeHeadingIds, rehypeAutolinkHeadings],
},
})

Without any further configuration, a level 2 heading like ## My heading will be transformed to the following HTML containing a link to the heading:

<h2 id="my-heading">
<a aria-hidden="true" tabindex="-1" href="#my-heading">
<span class="icon icon-link"></span>
</a>
My heading
</h2>

The plugin is configurable using various options to customize how the links are inserted, their content, attributes, and more.

The plugin does not add any styling to the links by default so you will need to add some yourself.

The goal of this section is to see how to generate links wrapping the heading text like the following example:

Further reading

Some random example text in Starlight.

Start by editing the plugin configuration in your astro.config.mjs file to update its various options and also define a custom CSS file that will contain the styling for the links:

export default defineConfig({
integrations: [
starlight({
title: 'My Docs',
customCss: [
// Load this additional CSS file using its relative path.
'./src/styles/headings.css',
],
}),
],
markdown: {
rehypePlugins: [
rehypeHeadingIds,
[
rehypeAutolinkHeadings,
{
// Wrap the heading text in a link.
behavior: 'wrap',
},
],
],
},
})

Add a headings.css file in your src/styles/ directory with the following content:

/* Style the Markdown heading links. */
.sl-markdown-content :is(h1, h2, h3, h4, h5, h6) > a {
color: var(--sl-color-white);
text-decoration: none;
&:hover {
text-decoration: underline;
}
}

Up to you to customize the plugin options and the CSS to match your needs! You may also want to check out this great article to make sure your anchor links are accessible.

You can find the complete source code of this guide in this StackBlitz example.