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:
Configure the plugin
Import the plugins in your astro.config.mjs
file to add them to the markdown.rehypePlugins
array:
Without any further configuration, a level 2 heading like ## My heading
will be transformed to the following HTML containing a link to the heading:
The plugin is configurable using various options to customize how the links are inserted, their content, attributes, and more.
Style the links
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:
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:
Add a headings.css
file in your src/styles/
directory with the following content:
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.