Skip to content

Anchors for headings

Introduction

There are different opinions on what is the best approach for those links. See:

Installation

Anchor before

I do like when an anchor is before heading (like in Github), but it doesn’t goes well with 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