# Heading Anchor

> A # beside every heading. It slides out of the margin when the heading is pointed at, or waits after the last word on a touch screen. Click it, or the heading, to put the section in the bar and copy the link.

Links · link, anchor, heading, permalink, copy, docs, wordpress · HTML, CSS, vanilla JS · no dependencies · updated 2026-10-27
Demo: https://kodza.dev/components/heading-anchor/
Source on GitHub: https://github.com/kodza-dev/kodza/tree/main/components/heading-anchor

## Files

The code below, served as files: byte for byte what the Kodza site copies (the CSS includes its theme guard).

- [`kodza-heading-anchor.css`](https://kodza.dev/registry/heading-anchor/kodza-heading-anchor.css) · 15.8 KB
- [`kodza-heading-anchor.js`](https://kodza.dev/registry/heading-anchor/kodza-heading-anchor.js) · 13.7 KB
- [`kodza-heading-anchor.html`](https://kodza.dev/registry/heading-anchor/kodza-heading-anchor.html) · 0.7 KB · the markup, to adapt and paste into your page

**Can you run shell commands? Download the CSS and the JS, don't retype them.** Retyping costs thousands of tokens and can drop or change lines of the CSS. Put the files where your stack expects them (Use it says where: change the `-o` paths):

```bash
curl -fsSL --create-dirs -o kodza/kodza-heading-anchor.css https://kodza.dev/registry/heading-anchor/kodza-heading-anchor.css
curl -fsSL --create-dirs -o kodza/kodza-heading-anchor.js https://kodza.dev/registry/heading-anchor/kodza-heading-anchor.js
```

Then load the files from your page as Use it shows, instead of pasting the content. The HTML is the part you adapt (text, links, modifiers): paste it from the Code section. Copy the CSS and the JS from the Code section only if you can't run commands, exactly as they are. (Windows PowerShell: `curl.exe`.)

## API

- Root: `[data-kodza-heading-anchor]`
- Variables (set them on the root element itself: it declares its own defaults):
  - `--kz-heading-anchor-heading: #0a0a0a`
  - `--kz-heading-anchor-text: rgba(10, 10, 10, 0.72)`
  - `--kz-heading-anchor-ink: currentColor`
  - `--kz-heading-anchor-muted: color-mix(in srgb, currentColor 50%, transparent)`
  - `--kz-heading-anchor-paper: #fff`
  - `--kz-heading-anchor-line: rgba(10, 10, 10, 0.1)`
  - `--kz-heading-anchor-gap: 0.3em`
  - `--kz-heading-anchor-size: 0.75em`
  - `--kz-heading-anchor-offset: 24px`
  - `--kz-heading-anchor-duration: 0.24s`
  - `--kz-heading-anchor-ease: cubic-bezier(0.22, 1, 0.36, 1)`
- Attributes:
  - `data-copied`
  - `data-failed`
  - `data-headings`
  - `data-kodza-heading-anchor`
  - `data-label`
  - `data-target`
- Lifecycle: `kodza:init` / `kodza:destroy` on `document`, with `{ detail: { root } }` to target a container.

## Keyboard

What each key does, by where the focus is. Keep it working when you adapt the HTML: same elements, same classes.

- On a heading link (focus in `.kodza-heading-anchor__link`):
  - `Enter`: Copies the section's link and puts it in the address bar

## Dark mode

The values Kodza uses on a dark background (`#0a0a0a`). For a page that follows the system theme, add them after the component's CSS:

```css
@media (prefers-color-scheme: dark) {
  .kodza-heading-anchor {
    --kz-heading-anchor-heading: #f2f2f0;
    --kz-heading-anchor-text: rgba(242, 242, 240, 0.72);
    --kz-heading-anchor-ink: #f2f2f0;
    --kz-heading-anchor-paper: #161616;
    --kz-heading-anchor-line: rgba(255, 255, 255, 0.12);
  }
}
```

A site with its own theme switch puts the same rules under its dark selector instead (`[data-theme="dark"] .kodza-heading-anchor { … }`); a single dark section, under that section's class.

## Use it

### Plain HTML page

- CSS: `kodza/kodza-heading-anchor.css` next to the page (the Files commands as they are), linked in `<head>`: `<link rel="stylesheet" href="kodza/kodza-heading-anchor.css">`. Without a shell, paste it in a `<style>` in `<head>` instead. It only touches `kodza-` classes.
- HTML: where the component goes. Paste it as many times as you need: instances never interfere.
- JS: `kodza/kodza-heading-anchor.js`, loaded with `<script src="kodza/kodza-heading-anchor.js" defer></script>` in `<head>`. Without a shell, paste it in a `<script>` before `</body>` (or in `<head>`: it waits for the page). One copy per page, whatever the number of instances.
- Restyle with the `--kz-…` variables, set on the component's root element itself (the root declares its own defaults, so a value on an ancestor is ignored), and with the modifiers / attributes listed under API.
- Font: it takes the page's own. The Kodza look is Geist: `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500&display=swap">`.
- Content added later (AJAX navigation, a SPA route, a builder preview): start it with `document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: container } }))`; before removing it, the same call with `'kodza:destroy'` stops it and puts the original markup back.

### Claude artifact (claude.ai)

- Paste the CSS in a `<style>` and the JS in a `<script>` at the end, in the artifact itself: it loads stylesheets only from Google Fonts and scripts only from a few CDNs, so no `<link>` or `<script src>` to Kodza.
- Writing the artifact file with a shell? Insert the downloaded files (Files) with a command instead of retyping them: a line `KODZA-CSS` alone inside the `<style>`, `KODZA-JS` inside the `<script>`, then `sed -e '/^KODZA-CSS$/{r kodza/kodza-heading-anchor.css' -e 'd' -e '}' -e '/^KODZA-JS$/{r kodza/kodza-heading-anchor.js' -e 'd' -e '}' page.html > artifact.html`.
- Font: load Geist from Google Fonts (allowed): `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500&display=swap">`.
- Dark mode: the viewer sets `data-theme="dark"` or `"light"` on `<html>`, or nothing when it follows the system. Write the Dark mode rules twice: inside `@media (prefers-color-scheme: dark)` with `:root:not([data-theme="light"])` in front of each selector, and with `:root[data-theme="dark"]` in front of each selector.

### WordPress

- HTML: a **Custom HTML** block (or a pattern / template part). WordPress keeps this markup as it is only for users allowed to post unfiltered HTML (Administrators; Super Admins on multisite): for anyone else it strips tags such as `<svg>`, `<input>` or `<dialog>`, so add it from the theme (a pattern or template part) instead.
- CSS and JS: the downloaded files go in the theme, under `wp-content/themes/<your-theme>/kodza/` (the child theme if there is one), enqueued from its functions.php (or a code-snippets plugin):
  ```php
  add_action('wp_enqueue_scripts', function () {
    $dir = get_stylesheet_directory() . '/kodza/';
    $uri = get_stylesheet_directory_uri() . '/kodza/';
    wp_enqueue_style('kodza-heading-anchor', $uri . 'kodza-heading-anchor.css', [], filemtime($dir . 'kodza-heading-anchor.css'));
    wp_enqueue_script('kodza-heading-anchor', $uri . 'kodza-heading-anchor.js', [], filemtime($dir . 'kodza-heading-anchor.js'), true);
  });
  ```
  Scoped to `kodza-` classes, the CSS never touches the theme. One copy of the JS, whatever the number of blocks.
- No access to the theme files? The CSS can also go, as it is, in **Appearance → Customize → Additional CSS** (classic theme) or **Styles → Additional CSS** in the Site Editor (block theme).
- Theme with AJAX page transitions: fire `kodza:init` on the new content after each swap (and `kodza:destroy` on the old one).
- Performance plugin (WP Rocket, LiteSpeed Cache, Perfmatters…) with **Delay JavaScript execution** turned on: add `kodza` to the scripts it must not delay. Otherwise the component waits for the visitor's first scroll, tap or mouse move, and that first click can be lost.
- Colours: it takes the colour of the text around it (or keeps its own monochrome): nothing to point at the theme.
- WordPress turns straight quotes and `--` into typographic ones in the text of a Custom HTML block (not inside `<code>` or `<pre>`).

#### With Elementor

- HTML: an **HTML** widget (Elementor shows it to administrators only). It keeps the code exactly as pasted, straight quotes included.
- CSS and JS: as above. Elementor's Site Settings → Theme Style styles every button, field, link and image of the page, components included; the theme guard at the end of the CSS keeps the component's buttons, fields and link colours as they are.
- The Elementor editor redraws each widget after the page has loaded: without the script below, the component stays still in the editor preview (the published page works). Add it once per site, in the footer like the component's script (`kodza/elementor-editor.js`, or a code-snippets plugin):

```js
// Kodza in the Elementor editor: the editor redraws each HTML widget after the page has loaded.
// Start Kodza in what it draws, stop it in what it replaces or removes. Once per site.
window.addEventListener('elementor/frontend/init', () => {
  if (!elementorFrontend.isEditMode()) return;
  class KodzaWidget extends elementorModules.frontend.handlers.Base {
    onInit() {
      super.onInit();
      this.kodza = [...this.$element[0].children];
      document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: this.$element[0] } }));
    }
    onDestroy() {
      super.onDestroy();
      this.kodza.forEach((root) => document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } })));
    }
  }
  elementorFrontend.elementsHandler.attachHandler('html', KodzaWidget);
});
```

- No child theme: everything can go in the HTML widget instead, `<style>` with the CSS, the HTML, then `<script>` with the JS. It works on the page and in the editor without the script above. This one reads the page around it, and a script in the widget runs before the rest of the page exists: put its `<script>` in an HTML widget at the bottom of the page instead.

### Shopify

- Files: `assets/kodza-heading-anchor.css` and `assets/kodza-heading-anchor.js` (the Files commands with `-o assets/…`).
- In the section: `{{ 'kodza-heading-anchor.css' | asset_url | stylesheet_tag }}` and `<script src="{{ 'kodza-heading-anchor.js' | asset_url }}" defer></script>`, then the HTML.
- The theme editor re-renders sections: restart them with
  `document.addEventListener('shopify:section:load', (e) => document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: e.target } })));`
  and the same with `shopify:section:unload` → `kodza:destroy`.

### React / Next.js

- Files, side by side (e.g. in `components/kodza/`): `HeadingAnchor.tsx` (below), the CSS block under Code saved as `heading-anchor.css` and the JS block as `heading-anchor.js`, both as they are. The HTML block is already inside the component: skip it.
- Use it: `import { HeadingAnchor } from '@/components/kodza/HeadingAnchor';` then `<HeadingAnchor />`. Props: `vars` (the `--kz-…` variables listed under API, e.g. `vars={{ '--kz-heading-anchor-heading': … }}`), `className`, `style` and the other props of its `<div>` (`onClick`, `aria-…`).
- Next.js App Router: it is a Client Component already (`'use client'`). Pages Router: Next.js takes global CSS only in `pages/_app`, so move the `import './heading-anchor.css'` line there.
- Safe under StrictMode, client-side navigation and prop changes: when a prop changes, the `key` gives React a fresh element, `kodza:destroy` stops the script on the old one and `kodza:init` starts it on the new one.
- Built from your data (tabs, rows, options)? Add what the markup is made of to the `key`, as plain values (ids, text, numbers). What the visitor changes (the open tab, the sort, what they type) is the script's: follow it with `onClick` or `onInput` on the root, and change it from your code as a visitor would (click the tab; set the field's value, then dispatch a bubbling `input` event). Fields stay uncontrolled (`defaultValue`, `name`).

```tsx
'use client';
// Kodza — Heading Anchor, for React. From https://kodza.dev/components/heading-anchor/
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Next to this file: heading-anchor.css and heading-anchor.js, the component's CSS and JS from Kodza, as they are.
// Yours to edit: the markup is plain JSX below.
// The script changes this markup once React has rendered it (it adds layers, splits text, moves
// nodes), so React must not patch it afterwards. When a prop changes, the key gives React a fresh
// element: kodza:destroy stops the script on the old one, kodza:init starts it on the new one.
// Built from your data (tabs, rows, options)? Put what the markup is made of in the key, as plain
// values (ids, text, numbers): a change starts the script again on fresh markup. What the visitor
// changes (the open tab, the sort, what they type) is the script's: keep it out of the key, follow
// it with onClick or onInput on the root, and change it from your code as a visitor would (click
// the tab; set the field's value, then dispatch a bubbling input event).
import { useRef, useEffect, type ComponentPropsWithoutRef, type ComponentRef, type CSSProperties } from 'react';
import './heading-anchor.css';

export type HeadingAnchorProps = Omit<ComponentPropsWithoutRef<'div'>, "children" | "vars"> & {
  /** Settings, as CSS variables on the root */
  vars?: {
    /** default: #0a0a0a */
    "--kz-heading-anchor-heading"?: string | number;
    /** default: rgba(10, 10, 10, 0.72) */
    "--kz-heading-anchor-text"?: string | number;
    /** default: currentColor */
    "--kz-heading-anchor-ink"?: string | number;
    /** default: color-mix(in srgb, currentColor 50%, transparent) */
    "--kz-heading-anchor-muted"?: string | number;
    /** default: #fff */
    "--kz-heading-anchor-paper"?: string | number;
    /** default: rgba(10, 10, 10, 0.1) */
    "--kz-heading-anchor-line"?: string | number;
    /** default: 0.3em */
    "--kz-heading-anchor-gap"?: string | number;
    /** default: 0.75em */
    "--kz-heading-anchor-size"?: string | number;
    /** default: 24px */
    "--kz-heading-anchor-offset"?: string | number;
    /** default: 0.24s */
    "--kz-heading-anchor-duration"?: string | number;
    /** default: cubic-bezier(0.22, 1, 0.36, 1) */
    "--kz-heading-anchor-ease"?: string | number;
  };
  className?: string;
};

export function HeadingAnchor({ vars, className, style, ...rest }: HeadingAnchorProps) {
  const ref = useRef<ComponentRef<'div'>>(null);
  const classes = ["kodza-heading-anchor", className].filter(Boolean).join(' ');
  // Everything the markup is made of: when it changes, React gets a fresh element (see the top)
  const key = JSON.stringify([classes, vars, style, rest]);

  // Starts the script on this element once React has rendered it, stops it when it goes
  useEffect(() => {
    const root = ref.current;
    let live = true;
    // @ts-ignore: a plain script, no types to find
    import('./heading-anchor.js').then(() => {
      if (live) document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root } }));
    });
    return () => {
      live = false;
      document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } }));
    };
  }, [key]);

  return (
    <div data-kodza-heading-anchor="" key={key} {...rest} className={classes} style={{ ...vars, ...style } as CSSProperties} ref={ref}>
      <h2>Install</h2>
      <p>Paste the markup, the CSS and the script. That's the install. No package, no build step, no config file to babysit.</p>
      <h3>In WordPress</h3>
      <p>Leave the block empty and drop it anywhere in the post: it finds the headings of the article around it. Your theme's titles keep their look.</p>
      <h2>Behind a sticky header</h2>
      <p>The script measures your fixed header and stops each section just below it. Nobody lands on a title hiding under the logo.</p>
      <h3>Ids, handled</h3>
      <p>Headings without an id get one from their text. It goes away when the script stops, so the HTML you saved stays the HTML you wrote.</p>
    </div>
  );
}
```

## Code

```html
<div class="kodza-heading-anchor" data-kodza-heading-anchor>
  <h2>Install</h2>
  <p>Paste the markup, the CSS and the script. That's the install. No package, no build step, no config file to babysit.</p>
  <h3>In WordPress</h3>
  <p>Leave the block empty and drop it anywhere in the post: it finds the headings of the article around it. Your theme's titles keep their look.</p>
  <h2>Behind a sticky header</h2>
  <p>The script measures your fixed header and stops each section just below it. Nobody lands on a title hiding under the logo.</p>
  <h3>Ids, handled</h3>
  <p>Headings without an id get one from their text. It goes away when the script stops, so the HTML you saved stays the HTML you wrote.</p>
</div>
```

```css
/* Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license */
/* Kodza — Heading Anchor
   A link to every heading. With a mouse and room on the left, a # slides out of the margin when
   the heading is pointed at or focused; on a touch screen, in a narrow column or under a centred
   heading, it waits after the last word. A click on it (with a mouse, on the heading too) puts the
   section's address in the bar and copies it: the # rolls up into a check and "Link copied" rolls
   in beside it.
   Tuned with the --kz-heading-anchor-* variables, on the root (for an empty root, on the article
   whose headings it links). By default the mark follows the heading's colour. */
.kodza-heading-anchor {
  --kz-heading-anchor-heading: #0a0a0a;
  --kz-heading-anchor-text: rgba(10, 10, 10, 0.72);
  --kz-heading-anchor-ink: currentColor;
  --kz-heading-anchor-muted: color-mix(in srgb, currentColor 50%, transparent);
  --kz-heading-anchor-paper: #fff;
  --kz-heading-anchor-line: rgba(10, 10, 10, 0.1);
  --kz-heading-anchor-gap: 0.3em;
  --kz-heading-anchor-size: 0.75em;
  --kz-heading-anchor-offset: 24px;
  --kz-heading-anchor-duration: 0.24s;
  --kz-heading-anchor-ease: cubic-bezier(0.22, 1, 0.36, 1);

  display: block;
}

/* The article it holds: its own type, whatever the theme gives to headings and paragraphs (an
   empty root leaves the page's own text as it is) */
.kodza-heading-anchor > h2,
.kodza-heading-anchor > h3 {
  color: var(--kz-heading-anchor-heading);
  font-family: "Geist", system-ui, sans-serif;
  font-weight: 600;
  text-align: start;
}

.kodza-heading-anchor > h2 {
  margin: 56px 0 14px;
  font-size: clamp(24px, 4vw, 32px);
  line-height: 1.2;
  letter-spacing: -0.035em;
}

.kodza-heading-anchor > h3 {
  margin: 36px 0 10px;
  font-size: 20px;
  line-height: 1.3;
  letter-spacing: -0.025em;
}

.kodza-heading-anchor > :is(h2, h3):first-child {
  margin-top: 0;
}

.kodza-heading-anchor > p {
  margin: 0 0 1.1em;
  color: var(--kz-heading-anchor-text);
  font-family: "Geist", system-ui, sans-serif;
  font-size: 17px;
  line-height: 1.7;
  text-wrap: pretty;
}

.kodza-heading-anchor > p:last-child {
  margin-bottom: 0;
}

/* The last word and the mark, kept on one line by the script */
.kodza-heading-anchor__tie {
  white-space: nowrap;
}

/* After the last word (touch screens, narrow columns, centred headings, and the default) */
.kodza-heading-anchor__link {
  position: relative;
  display: inline;
  margin: 0 0 0 var(--kz-heading-anchor-gap, 0.3em);
  padding: 0;
  border: 0;
  border-radius: 6px;
  background: none;
  color: var(--kz-heading-anchor-ink, currentColor);
  font: inherit;
  letter-spacing: 0;
  text-decoration: none;
  text-transform: none;
  white-space: nowrap;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
}

.kodza-heading-anchor__link:dir(rtl) {
  margin: 0 var(--kz-heading-anchor-gap, 0.3em) 0 0;
}

.kodza-heading-anchor__link:focus-visible {
  outline: 2px solid var(--kz-heading-anchor-ink, currentColor);
  outline-offset: 3px;
}

/* The mark: the # and the check share one masked cell, and take turns in it */
.kodza-heading-anchor__glyph {
  display: inline-grid;
  place-items: center;
  vertical-align: baseline;
  clip-path: inset(0);
}

.kodza-heading-anchor__hash,
.kodza-heading-anchor__check {
  grid-area: 1 / 1;
  transition: translate var(--kz-heading-anchor-duration, 0.24s) var(--kz-heading-anchor-ease, cubic-bezier(0.22, 1, 0.36, 1));
}

.kodza-heading-anchor__hash {
  padding: 0 0.04em;
  color: var(--kz-heading-anchor-muted, color-mix(in srgb, currentColor 50%, transparent));
  font: 500 var(--kz-heading-anchor-size, 0.75em)/1.15 "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;
  transition-property: translate, transform, color;
}

.kodza-heading-anchor__link:hover .kodza-heading-anchor__hash,
.kodza-heading-anchor__link:focus-visible .kodza-heading-anchor__hash {
  color: var(--kz-heading-anchor-ink, currentColor);
}

.kodza-heading-anchor__check {
  width: calc(var(--kz-heading-anchor-size, 0.75em) * 0.82);
  height: calc(var(--kz-heading-anchor-size, 0.75em) * 0.82);
  overflow: visible;
  fill: none;
  stroke: currentColor;
  stroke-width: 2;
  stroke-linecap: round;
  stroke-linejoin: round;
  translate: 0 110%;
}

.kodza-heading-anchor__check path {
  stroke-dasharray: 1;
  stroke-dashoffset: 1;
  transition: stroke-dashoffset 0.2s ease;
}

/* In the margin: level with the first line, its baseline on the heading's baseline. Hidden in its
   mask until the heading is pointed at or the link focused, then it slides out of the text. */
.kodza-heading-anchor__link.is-margin {
  position: absolute;
  top: var(--kz-heading-anchor-top, 0px);
  right: calc(100% + var(--kz-heading-anchor-gap, 0.3em));
  display: block;
  margin: 0;
}

.kodza-heading-anchor__link.is-margin:dir(rtl) {
  right: auto;
  left: calc(100% + var(--kz-heading-anchor-gap, 0.3em));
}

/* The way from the heading to the mark stays a hover */
.kodza-heading-anchor__link.is-margin::before {
  content: "";
  position: absolute;
  inset: 0 calc(-1 * var(--kz-heading-anchor-gap, 0.3em)) 0 -0.2em;
}

.kodza-heading-anchor__link.is-margin:dir(rtl)::before {
  inset: 0 -0.2em 0 calc(-1 * var(--kz-heading-anchor-gap, 0.3em));
}

.kodza-heading-anchor__link.is-margin .kodza-heading-anchor__hash {
  translate: 100% 0;
}

.kodza-heading-anchor__link.is-margin:dir(rtl) .kodza-heading-anchor__hash {
  translate: -100% 0;
}

@media (hover: hover) {
  :is(h1, h2, h3, h4, h5, h6):hover > .kodza-heading-anchor__link.is-margin .kodza-heading-anchor__hash,
  :is(h1, h2, h3, h4, h5, h6):hover > .kodza-heading-anchor__tie > .kodza-heading-anchor__link.is-margin .kodza-heading-anchor__hash {
    translate: 0 0;
  }
}

/* With a mouse the whole heading copies its link: pointing at it shows the hand and inks the # */
@media (hover: hover) and (pointer: fine) {
  :is(h1, h2, h3, h4, h5, h6):has(> .kodza-heading-anchor__link, > .kodza-heading-anchor__tie > .kodza-heading-anchor__link) {
    cursor: pointer;
  }

  :is(h1, h2, h3, h4, h5, h6):hover > .kodza-heading-anchor__link .kodza-heading-anchor__hash,
  :is(h1, h2, h3, h4, h5, h6):hover > .kodza-heading-anchor__tie > .kodza-heading-anchor__link .kodza-heading-anchor__hash {
    color: var(--kz-heading-anchor-ink, currentColor);
  }
}

.kodza-heading-anchor__link.is-margin:focus-visible .kodza-heading-anchor__hash {
  translate: 0 0;
}

/* Copied: the # rolls up out of its cell, the check comes up behind it, drawing itself on the way */
.kodza-heading-anchor__link.is-copied .kodza-heading-anchor__hash {
  transform: translateY(-110%);
}

.kodza-heading-anchor__link.is-copied .kodza-heading-anchor__check {
  translate: 0 0;
}

.kodza-heading-anchor__link.is-copied .kodza-heading-anchor__check path {
  stroke-dashoffset: 0;
  transition: stroke-dashoffset 0.3s var(--kz-heading-anchor-ease, cubic-bezier(0.22, 1, 0.36, 1));
}

/* "Link copied", beside the mark on the side away from the text, its word rolling in its mask.
   Centred on the # (in the heading's em: the # sits on the baseline, lower than the box centre) */
.kodza-heading-anchor__label {
  position: absolute;
  top: 50%;
  left: calc(100% + 0.6rem);
  display: grid;
  clip-path: inset(0 -2px);
  color: var(--kz-heading-anchor-ink, currentColor);
  white-space: nowrap;
  pointer-events: none;
  transform: translateY(calc(-50% + 0.075em));
}

.kodza-heading-anchor__link:dir(rtl) .kodza-heading-anchor__label,
.kodza-heading-anchor__link.is-margin .kodza-heading-anchor__label {
  right: calc(100% + 0.6rem);
  left: auto;
}

.kodza-heading-anchor__link.is-margin:dir(rtl) .kodza-heading-anchor__label {
  right: auto;
  left: calc(100% + 0.6rem);
}

.kodza-heading-anchor__word {
  font: 500 12px/1.5 "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;
  letter-spacing: 0;
  translate: 0 110%;
  transition: translate var(--kz-heading-anchor-duration, 0.24s) var(--kz-heading-anchor-ease, cubic-bezier(0.22, 1, 0.36, 1));
}

.kodza-heading-anchor__link.is-copied .kodza-heading-anchor__word {
  translate: 0 0;
  transition-delay: 0.06s;
}

/* No room beside it: above the mark, on a small sheet */
.kodza-heading-anchor__link.is-above .kodza-heading-anchor__label,
.kodza-heading-anchor__link.is-above:dir(rtl) .kodza-heading-anchor__label {
  top: auto;
  right: auto;
  bottom: calc(100% + 6px);
  left: 50%;
  padding: 4px 9px;
  border: 1px solid var(--kz-heading-anchor-line, rgba(10, 10, 10, 0.1));
  border-radius: 8px;
  background: var(--kz-heading-anchor-paper, #fff);
  box-shadow: 0 6px 18px rgba(10, 10, 10, 0.08);
  color: var(--kz-heading-anchor-ink, #0a0a0a);
  clip-path: inset(-1px -1px -1px -1px round 8px);
  opacity: 0;
  transform: translate(-50%, 4px);
  transition: opacity 0.18s ease, transform var(--kz-heading-anchor-duration, 0.24s) var(--kz-heading-anchor-ease, cubic-bezier(0.22, 1, 0.36, 1));
}

.kodza-heading-anchor__link.is-above.is-copied .kodza-heading-anchor__label {
  opacity: 1;
  transform: translate(-50%, 0);
}

.kodza-heading-anchor__link.is-above .kodza-heading-anchor__word {
  translate: 0 0;
  transition: none;
}

/* For screen readers: what happened after the click */
.kodza-heading-anchor__status {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

@media (prefers-reduced-motion: reduce) {
  .kodza-heading-anchor__link *,
  .kodza-heading-anchor__link::before {
    transition-duration: 0.01ms !important;
    transition-delay: 0s !important;
  }
}

/* kodza-guard dba5956bf4eb — generated by Kodza, do not edit.
   Theme guard: keeps a site's own CSS (WordPress themes, Bootstrap, CSS resets…) off this
   component. :not(#_) is always true and weighs as much as an id, so these lines win over
   theme rules made of classes and tags. Customise the component through its --kz-* variables. */

/* What the browser gives, where the component sets it only in some states: at the lowest weight, so its own rules below put it back */

:where(.kodza-heading-anchor__link):not(#_) {
  outline: revert;
  outline-offset: revert;
}

/* What the browser gives, on everything the component leaves to it */

.kodza-heading-anchor:not(#_),
.kodza-heading-anchor__tie:not(#_),
.kodza-heading-anchor__glyph:not(#_),
.kodza-heading-anchor__hash:not(#_),
.kodza-heading-anchor__label:not(#_),
.kodza-heading-anchor__word:not(#_),
.kodza-heading-anchor__status:not(#_) {
  box-sizing: revert;
}

.kodza-heading-anchor__link:not(#_) {
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  float: revert;
  box-shadow: revert;
  appearance: revert;
  max-width: revert;
  max-height: revert;
  text-underline-offset: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
}

.kodza-heading-anchor__check:not(#_) {
  border: revert;
  margin: revert;
  padding: revert;
  border-radius: revert;
  outline: revert;
  text-decoration: revert;
  list-style: revert;
  box-sizing: revert;
  float: revert;
  position: revert;
  background-color: revert;
  background-image: revert;
  box-shadow: revert;
  outline-offset: revert;
  appearance: revert;
  max-width: revert;
  max-height: revert;
  color: revert;
  font-family: revert;
  font-size: revert;
  font-weight: revert;
  font-style: revert;
  line-height: revert;
  letter-spacing: revert;
  text-transform: revert;
  text-underline-offset: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
}

.kodza-heading-anchor h2:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_),
.kodza-heading-anchor h3:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_) {
  border: revert;
  padding: revert;
  border-radius: revert;
  outline: revert;
  text-decoration: revert;
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  float: revert;
  position: revert;
  background-color: revert;
  background-image: revert;
  box-shadow: revert;
  outline-offset: revert;
  appearance: revert;
  max-width: revert;
  max-height: revert;
  font-style: revert;
  text-transform: revert;
  text-underline-offset: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
}

.kodza-heading-anchor p:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_) {
  border: revert;
  padding: revert;
  border-radius: revert;
  outline: revert;
  text-decoration: revert;
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  float: revert;
  position: revert;
  background-color: revert;
  background-image: revert;
  box-shadow: revert;
  outline-offset: revert;
  appearance: revert;
  max-width: revert;
  max-height: revert;
  font-weight: revert;
  font-style: revert;
  letter-spacing: revert;
  text-transform: revert;
  text-underline-offset: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
}

.kodza-heading-anchor__check:not(#_):where(:not([hidden])),
.kodza-heading-anchor h2:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_):where(:not([hidden])),
.kodza-heading-anchor p:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_):where(:not([hidden])),
.kodza-heading-anchor h3:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_):where(:not([hidden])) {
  display: revert;
}

.kodza-heading-anchor__check:not(#_):where([hidden]),
.kodza-heading-anchor h2:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_):where([hidden]),
.kodza-heading-anchor p:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_):where([hidden]),
.kodza-heading-anchor h3:where(:not([class*="kodza-"]):not(.kodza-heading-anchor [class*="kodza-"] *)):not(#_):where([hidden]) {
  display: none;
}

.kodza-heading-anchor__link:not(#_)::before {
  box-sizing: revert;
}

/* The component's own rules, one step stronger: real buttons and fields, what it sets on tags themes style (links, lists, headings, images…), and the root width (a theme may narrow it, never widen it) */

.kodza-heading-anchor > h2:not(#_),
.kodza-heading-anchor > h3:not(#_) {
  color: var(--kz-heading-anchor-heading);
  font-family: "Geist", system-ui, sans-serif;
  font-weight: 600;
  text-align: start;
}

.kodza-heading-anchor > h2:not(#_) {
  margin: 56px 0 14px;
  font-size: clamp(24px, 4vw, 32px);
  line-height: 1.2;
  letter-spacing: -0.035em;
}

.kodza-heading-anchor > h3:not(#_) {
  margin: 36px 0 10px;
  font-size: 20px;
  line-height: 1.3;
  letter-spacing: -0.025em;
}

.kodza-heading-anchor > :is(h2, h3):first-child:where(h2, p, h3):not(#_) {
  margin-top: 0;
}

.kodza-heading-anchor > p:not(#_) {
  margin: 0 0 1.1em;
  color: var(--kz-heading-anchor-text);
  font-family: "Geist", system-ui, sans-serif;
  font-size: 17px;
  line-height: 1.7;
}

.kodza-heading-anchor > p:last-child:not(#_) {
  margin-bottom: 0;
}

.kodza-heading-anchor__link:not(#_) {
  position: relative;
  display: inline;
  margin: 0 0 0 var(--kz-heading-anchor-gap, 0.3em);
  padding: 0;
  border: 0;
  border-radius: 6px;
  background: none;
  color: var(--kz-heading-anchor-ink, currentColor);
  font: inherit;
  letter-spacing: 0;
  text-decoration: none;
  text-transform: none;
}

.kodza-heading-anchor__link:dir(rtl):not(#_) {
  margin: 0 var(--kz-heading-anchor-gap, 0.3em) 0 0;
}

.kodza-heading-anchor__link:focus-visible:not(#_) {
  outline: 2px solid var(--kz-heading-anchor-ink, currentColor);
  outline-offset: 3px;
}

.kodza-heading-anchor__check:not(#_) {
  transition: translate var(--kz-heading-anchor-duration, 0.24s) var(--kz-heading-anchor-ease, cubic-bezier(0.22, 1, 0.36, 1));
}

.kodza-heading-anchor__link.is-margin:not(#_) {
  position: absolute;
  display: block;
  margin: 0;
}

@media (prefers-reduced-motion: reduce) {
  .kodza-heading-anchor__link *:where(svg):not(#_) {
    transition-duration: 0.01ms !important;
    transition-delay: 0s !important;
  }
}
```

```js
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Kodza — Heading Anchor
// Gives every heading a link to itself: a # in the margin (after the last word on a touch screen,
// in a narrow column or a centred heading) that puts the section's address in the bar and copies it.
// With a mouse, a click on the heading does the same.
// Headings without an id get one, removed again when the script stops. An empty root works on the
// headings of the article around or beside it (data-target), like a Custom HTML block in WordPress.
(() => {
  const SELECTOR = '[data-kodza-heading-anchor]';
  const RESET_AFTER = 1800;
  const pointer = window.matchMedia('(hover: hover) and (pointer: fine)');

  // One link, written once and copied for each heading
  const MARK = document.createElement('template');
  MARK.innerHTML = '<a class="kodza-heading-anchor__link"><span class="kodza-heading-anchor__glyph" aria-hidden="true"><span class="kodza-heading-anchor__hash">#</span><svg class="kodza-heading-anchor__check" viewBox="0 0 16 16"><path d="M3 8.5l3.2 3L13 4.5" pathLength="1" /></svg></span><span class="kodza-heading-anchor__label" aria-hidden="true"><span class="kodza-heading-anchor__word"></span></span></a>';

  const slug = (text) => text.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'section';

  async function writeText(text) {
    try {
      await navigator.clipboard.writeText(text);
      return true;
    } catch {
      const area = document.createElement('textarea');
      area.value = text;
      area.setAttribute('readonly', '');
      area.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none';
      document.body.append(area);
      area.select();
      let ok = false;
      try {
        ok = document.execCommand('copy');
      } catch {}
      area.remove();
      return ok;
    }
  }

  // The bottom of what stays at the top of the window (a fixed or sticky header): a section reached
  // by its link starts below it, not under it
  function headerBottom() {
    const width = document.documentElement.clientWidth;
    let bottom = 0;
    [width / 2, 24, width - 24].forEach((x) => {
      for (let el = document.elementFromPoint(x, 1); el && el !== document.body && el !== document.documentElement; el = el.parentElement) {
        const { position } = getComputedStyle(el);
        if (position !== 'fixed' && position !== 'sticky') continue;
        const rect = el.getBoundingClientRect();
        if (rect.top <= 1 && rect.height < window.innerHeight / 2) bottom = Math.max(bottom, rect.bottom);
        break;
      }
    });
    return bottom;
  }

  // One instance, with its own state: two copies on a page never interfere. Everything it
  // starts is tied to `signal` (listeners get { signal }, observers and timers stop on its
  // 'abort' event), so kodza:destroy stops it all.
  function mount(root, signal) {
    const which = root.dataset.headings || 'h2, h3';
    let scope = root;
    let headings = [...root.querySelectorAll(which)];
    if (!headings.length) {
      const selector = root.dataset.target || 'article, main, .entry-content';
      scope = root.parentElement?.closest(selector);
      for (let up = root.parentElement; !scope && up; up = up.parentElement) scope = up.querySelector(selector);
      headings = scope ? [...scope.querySelectorAll(which)] : [];
    }
    // Not the headings of another component, nor those that already hold a link
    headings = headings.filter((heading) => {
      const owner = heading.parentElement.closest('[class*="kodza-"]');
      return /^H[1-6]$/.test(heading.tagName) && heading.textContent.trim() && (!owner || owner === root)
        && !heading.querySelector('a[href]') && !heading.closest('a[href]');
    });
    if (!headings.length) return;

    const label = root.dataset.label || 'Copy link';
    const copied = root.dataset.copied || 'Link copied';
    const failed = root.dataset.failed || 'In the address bar';
    const status = document.createElement('span');
    status.className = 'kodza-heading-anchor__status';
    status.setAttribute('role', 'status');
    root.append(status);

    const items = headings.map((heading) => {
      const item = { heading, named: !heading.id, timer: 0 };
      if (item.named) {
        let id = slug(heading.textContent);
        for (let n = 2; document.getElementById(id); n++) id = `${slug(heading.textContent)}-${n}`;
        heading.id = id;
      }
      const link = MARK.content.firstElementChild.cloneNode(true);
      link.href = `#${heading.id}`;
      link.setAttribute('aria-label', label);
      item.link = link;
      item.hash = link.querySelector('.kodza-heading-anchor__hash');
      item.word = link.querySelector('.kodza-heading-anchor__word');
      item.text = link.querySelector('.kodza-heading-anchor__label');
      // The mark never starts a line on its own: it is tied to the last word
      const last = heading.lastChild;
      if (last?.nodeType === Node.TEXT_NODE && /\S\s*$/.test(last.data)) {
        const at = last.data.search(/\S+\s*$/);
        const word = at > 0 ? last.splitText(at) : last;
        const end = word.data.search(/\s*$/);
        if (end < word.data.length) word.splitText(end);
        item.tie = document.createElement('span');
        item.tie.className = 'kodza-heading-anchor__tie';
        word.before(item.tie);
        item.tie.append(word, link);
      } else {
        heading.append(link);
      }
      const style = getComputedStyle(heading);
      item.style = { position: heading.style.position, scroll: heading.style.scrollMarginTop };
      item.ownScroll = parseFloat(style.scrollMarginTop) > 0;
      if (style.position === 'static') heading.style.position = 'relative';
      return item;
    });

    // In the margin on a real pointer, when every heading has room on its start side and starts its
    // lines there; after the last word otherwise. The scroll margin follows the header.
    const layout = () => {
      if (!root.isConnected) return;
      const width = document.documentElement.clientWidth;
      const was = items.map(({ link, heading }) => {
        link.style.setProperty('--kz-heading-anchor-top', getComputedStyle(heading).paddingTop);
        const on = link.classList.contains('is-margin');
        link.classList.add('is-margin');
        return on;
      });
      const margin = pointer.matches && items.every(({ heading, link }) => {
        const style = getComputedStyle(heading);
        const ltr = style.direction !== 'rtl';
        if (!['start', 'justify', ltr ? 'left' : 'right'].includes(style.textAlign)) return false;
        const rect = link.getBoundingClientRect();
        return ltr ? rect.left >= 8 : rect.right <= width - 8;
      });
      // A mark that changes side gets there without sliding
      items.forEach(({ link, hash }, i) => {
        if (!margin) link.classList.remove('is-margin');
        if (was[i] !== margin) hash.getAnimations().forEach((animation) => animation.finish());
      });
      const padded = parseFloat(getComputedStyle(document.documentElement).scrollPaddingTop) > 0;
      const offset = parseFloat(getComputedStyle(items[0].link).getPropertyValue('--kz-heading-anchor-offset')) || 24;
      const top = padded ? 0 : Math.round(headerBottom() + offset);
      items.forEach(({ heading, ownScroll }) => {
        if (!ownScroll && !padded) heading.style.scrollMarginTop = `${top}px`;
      });
    };

    // Beside the mark on the side away from the text when it fits, above it otherwise
    const show = (item, ok) => {
      const { link, word, text, heading } = item;
      clearTimeout(item.timer);
      word.textContent = ok ? copied : failed;
      link.classList.remove('is-above');
      const ltr = getComputedStyle(heading).direction !== 'rtl';
      const mark = link.getBoundingClientRect();
      const room = text.getBoundingClientRect().width + 12;
      const box = heading.getBoundingClientRect();
      const fits = link.classList.contains('is-margin')
        ? (ltr ? mark.left - room >= 8 : mark.right + room <= document.documentElement.clientWidth - 8)
        : (ltr ? mark.right + room <= box.right : mark.left - room >= box.left);
      link.classList.toggle('is-above', !fits);
      text.getAnimations({ subtree: true }).forEach((animation) => animation.finish()); // it changes side without sliding
      link.classList.add('is-copied');
      status.textContent = ok ? copied : `Couldn't copy. The link is ${failed.toLowerCase()}.`;
      item.timer = setTimeout(() => {
        link.classList.remove('is-copied');
        status.textContent = '';
      }, RESET_AFTER);
    };

    const copy = async (item) => {
      history.replaceState(history.state, '', `#${item.heading.id}`);
      const ok = await writeText(location.href);
      if (!signal.aborted) show(item, ok);
    };
    const plain = (event) => !event.button && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey;

    items.forEach((item) => {
      item.link.addEventListener('click', (event) => {
        if (!plain(event)) return; // a new tab, a new window
        event.preventDefault();
        copy(item);
      }, { signal });
      // With a mouse, the heading itself does what its mark does: not while its words are being
      // selected, nor from a control written in it
      item.heading.addEventListener('click', (event) => {
        if (!pointer.matches || !plain(event) || event.defaultPrevented) return;
        if (event.target.closest('a, button, input, select, textarea, label, summary')) return;
        if (getSelection()?.toString().trim()) return;
        copy(item);
      }, { signal });
    });

    let frame = 0;
    const later = () => {
      cancelAnimationFrame(frame);
      frame = requestAnimationFrame(layout);
    };
    const observer = new ResizeObserver(later);
    layout();
    observer.observe(scope);
    window.addEventListener('resize', later, { signal });
    pointer.addEventListener('change', later, { signal });
    document.fonts?.ready.then(() => {
      if (!signal.aborted) layout();
    });

    // Arriving on a section named here: the browser looked for it before it had its id
    let target = null;
    try {
      target = items.find(({ heading, named }) => named && `#${heading.id}` === decodeURIComponent(location.hash));
    } catch {}
    if (target) target.heading.scrollIntoView({ block: 'start' });

    signal.addEventListener('abort', () => {
      observer.disconnect();
      cancelAnimationFrame(frame);
      status.remove();
      items.forEach((item) => {
        clearTimeout(item.timer);
        const { heading, link, tie } = item;
        link.remove();
        if (tie) {
          tie.replaceWith(...tie.childNodes);
          heading.normalize();
        }
        heading.style.position = item.style.position;
        heading.style.scrollMarginTop = item.style.scroll;
        if (!heading.getAttribute('style')) heading.removeAttribute('style');
        if (item.named) heading.removeAttribute('id');
      });
    });
  }

  // Kodza lifecycle, the same in every component: `kodza:init` starts the instances inside
  // event.detail.root (the whole page by default), `kodza:destroy` stops them and puts their
  // markup back. For themes and apps that swap content without a page load. Each running root
  // keeps its markup as written under KODZA, shared by every Kodza script on the page: a Kodza
  // component inside another one is saved as written, not half-started, and stopped with it.
  const KODZA = Symbol.for('kodza');
  const instances = new WeakMap();
  const find = (scope = document) => [scope, ...scope.querySelectorAll(SELECTOR)].filter((el) => el.matches?.(SELECTOR));
  const attrsOf = (el) => [...el.attributes].map((a) => [a.name, a.value]);
  const put = (el, saved) => {
    [...el.attributes].forEach((a) => el.removeAttribute(a.name));
    saved.attrs.forEach(([name, value]) => el.setAttribute(name, value));
    el.innerHTML = saved.html;
  };
  // The markup inside a root as written: Kodza components already running in it give back their own
  const written = (root) => {
    const all = [...root.querySelectorAll('*')];
    if (!all.some((el) => el[KODZA])) return root.innerHTML;
    const copy = root.cloneNode(true);
    const twins = copy.querySelectorAll('*');
    let last = null;
    all.forEach((el, i) => {
      if (!el[KODZA] || last?.contains(el)) return;
      last = el;
      put(twins[i], el[KODZA]);
    });
    return copy.innerHTML;
  };
  const init = (scope) => find(scope).forEach((root) => {
    if (root.classList.contains('is-ready')) return; // already running, maybe from another copy of this script
    const controller = new AbortController();
    const saved = { html: written(root), attrs: attrsOf(root), stop: () => destroy(root) };
    instances.set(root, { controller, saved });
    root[KODZA] = saved;
    mount(root, controller.signal);
    root.classList.add('is-ready');
  });
  const destroy = (scope) => find(scope).forEach((root) => {
    const instance = instances.get(root);
    if (!instance) return;
    instances.delete(root);
    // The Kodza components running inside it stop first: once its markup is put back, their own
    // script could not find them any more
    root.querySelectorAll('*').forEach((el) => el[KODZA]?.stop());
    instance.controller.abort();
    delete root[KODZA];
    put(root, instance.saved);
  });
  document.addEventListener('kodza:init', (event) => init(event.detail?.root));
  document.addEventListener('kodza:destroy', (event) => destroy(event.detail?.root));
  init();
  // Loaded in <head>, the script runs before the markup exists: once more when it is parsed
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => init(), { once: true });
})();
```

Free to use, from Kodza (https://kodza.dev).
