Deep Linking
Browsers allow you to deep link to any element via the ID. This is accomplished with an anchor tag and hashed (#
) href value. When interacting with these anchors, the viewport will automatically attempt to scroll the <body>
element and bring the element into view.
<h2 class="#some-example-slug">Some Example Heading<h2>
<a href="#real-world-example" class="anchor">Some Example Heading</a>
TIP: If you abstract scrolling away from the
<body>
element, this will not work.
Scroll Behavior
You may optionally choose to implement a smooth scroll behavior using CSS.
<body class="smooth-scroll">
body { scroll-behavior: smooth; }
Generate a Slug
The following provides a barebones implementation for generating a slug based on a heading text value.
function generateSlug(text: string, prefix?: string = '', suffix?: string = '') { // Format the slug from the text value. const slug = text .toLowerCase() .replaceAll(/[^a-zA-Z0-9 ]/g, '') .replaceAll(' ', '-') .toLowerCase(); // Note that you can optionally apply a prefix/suffix. return `${prefix}${slug}${suffix}`;}
// UsagegenerateSlug('An Example Header'); // result: an-example-headergenerateSlug('An Example Header', 'skeleton-'); // result: skeleton-an-example-headergenerateSlug('An Example Header', '', '-skeleton'); // result: an-example-header-skeleton
Guides
Specific instructions for generating headings will differ based on your meta-framework and your application architecture. Below are a few suggestions, but this is neither a definitive or exhaustive list of all available options.
- Astro - enables you to automatically generate headings using built-in MDX features.
- Svelte - Melt UI provides a headless component solution for Svelte.
- Next.js - Nextra provides a headless component solution for Next.js + MDX.
- Rehype Plugin - a general purpose Rehype plugin for generating a table of contents.