Skip to content

Anchors for headings

Introduction

There are different opinions on the best approach for these links. See:

Installation

Anchor before

I prefer when an anchor is placed before the heading (like in GitHub), but it doesn’t work well with the Starlight design.

  1. Install dependencies

    Terminal window
    pnpm add rehype-autolink-headings @astrojs/markdown-remark
  2. Configure Astro

    astro.config.mjs
    import { rehypeHeadingIds } from "@astrojs/markdown-remark";
    import rehypeAutolinkHeadings from "rehype-autolink-headings";
    export default defineConfig({
    integrations: [
    starlight({
    customCss: ["./src/styles/custom.css"],
    }),
    ],
    markdown: {
    rehypePlugins: [rehypeHeadingIds, rehypeAutolinkHeadings],
    },
    });
  3. Add CSS

    src/styles/custom.css
    .sl-markdown-content :is(h1, h2, h3, h4, h5, h6) {
    a {
    color: var(--sl-color-black);
    text-decoration: none;
    font-size: 1.5rem;
    margin-left: calc(-1rem - 4px);
    padding-right: 4px;
    }
    &:hover a {
    color: var(--sl-color-accent);
    }
    .icon.icon-link::after {
    content: "#";
    }
    }

Anchor after

  1. Install dependencies

    Terminal window
    pnpm add rehype-autolink-headings @astrojs/markdown-remark
  2. Configure Astro

    astro.config.mjs
    import { rehypeHeadingIds } from "@astrojs/markdown-remark";
    import rehypeAutolinkHeadings from "rehype-autolink-headings";
    export default defineConfig({
    integrations: [
    starlight({
    customCss: ["./src/styles/custom.css"],
    }),
    ],
    markdown: {
    rehypePlugins: [
    rehypeHeadingIds,
    [rehypeAutolinkHeadings, { behavior: "append" }],
    ],
    },
    });
  3. Add CSS

    src/styles/custom.css
    .sl-markdown-content :is(h1, h2, h3, h4, h5, h6) {
    a {
    color: var(--sl-color-black);
    text-decoration: none;
    font-size: 1.5rem;
    margin-left: 0.5rem;
    }
    &:hover a {
    color: var(--sl-color-accent);
    }
    .icon.icon-link::after {
    content: "#";
    }
    }

See also