Sub topic 13
Link between sections with anchors and smooth scrolling
This chapter assumes you already have the page skeleton, semantic landmarks, and a linked stylesheet from earlier chapters. You should also know what an id attribute is and how a CSS rule selects an element. By the end, the navigation in your page will jump to sections, stop under a sticky header, scroll smoothly, and behave for keyboard users and people who dislike motion.
How fragment links work
A fragment link is an href that starts with # followed by an id value. When you activate it, the browser does four things:
- It looks for an element in the current document whose
idmatches the text after the#. - It scrolls that element into view.
- It adds the fragment to the address bar, for example
index.html#projects. - It records a history entry, so the Back button returns to the previous scroll position.
No JavaScript is involved. The skeleton from the first chapter already does this:
<nav aria-label="Main">
<ul>
<li><a href="#about">About</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<main id="main">
<section id="about">
<h1>Jane Doe</h1>
<p>I build small, fast websites.</p>
</section>
<section id="projects">
<h2>Projects</h2>
</section>
<section id="contact">
<h2>Contact</h2>
</section>
</main>The link text and the target are connected only by the id. Because of that, most failures come from a mismatch between the two.
Rules for ids
- An
idmust be unique in the document. With duplicates, the browser scrolls to the first match and ignores the rest. - Matching is case-sensitive.
#Projectsdoes not findid="projects". - An
idcannot contain spaces. Use lowercase words joined with hyphens, such asid="contact-me". - Name an
idafter the content, not the look.id="projects"survives a redesign.id="blue-box"does not. - A fragment that matches nothing does not raise an error. The URL changes and the page stays where it is.
Two fragments have special meaning. href="#" and href="#top" scroll to the top of the page, even if no element has that id. A "back to top" link can therefore be written as <a href="#top">Back to top</a>.
Style the target with :target
The :target pseudo-class matches the element that the current URL fragment points to. You can use it to show the visitor where they landed:
section:target h1,
section:target h2 {
color: var(--color-accent);
}This also works when someone opens a shared link such as index.html#contact directly. The matching section is highlighted on load.
Add smooth scrolling
By default, the jump is instant. One declaration on the root element makes the browser animate it:
html {
scroll-behavior: smooth;
}Put it on html, not body. The root element is the scroll container for the whole page. Putting it on body usually has no effect, because body is not what scrolls.
Smooth scrolling is not suitable for everyone. Some visitors get dizzy or nauseous from animated motion, and they set "reduce motion" in their operating system. Browsers pass this setting to CSS as prefers-reduced-motion. The safest approach is to opt in only when the visitor has no such preference:
@media (prefers-reduced-motion: no-preference) {
html {
scroll-behavior: smooth;
}
}The version from the topic's earlier example does the reverse. It enables smooth scrolling for everyone and switches it off with prefers-reduced-motion: reduce. Both work. The opt-in form has one advantage: a browser that does not understand the media query falls back to instant scrolling, which is the safe default.
Fix content hidden under a sticky header
A common problem appears once the header is made sticky. The browser aligns the top edge of the target with the top edge of the viewport, so the sticky header covers the first lines of the section. Making the header sticky takes two declarations:
:root {
--header-height: 4rem;
}
header {
position: sticky;
top: 0;
z-index: 10;
display: flex;
align-items: center;
justify-content: center;
height: var(--header-height);
background: var(--color-bg);
}Then tell each target to stop short of the top edge. The property for this is scroll-margin-top, set on the target:
section[id] {
scroll-margin-top: calc(var(--header-height) + var(--space));
}scroll-margin-top adds space around the element for scroll alignment only. It does not change layout, so no gap appears on the page.
There is a second property with a similar name, and the two are easy to confuse:
| Property | Set on | Effect |
|---|---|---|
| `scroll-margin-top` | The target element | Moves that element's snap position away from the top edge. |
| `scroll-padding-top` | The scroll container, usually `html` | Shrinks the usable scrolling area for every target inside it. |
For a page with one sticky header, either works. scroll-padding-top on html covers all targets with one rule, including ones you add later. scroll-margin-top lets individual sections differ. Pick one and do not apply both, or the offsets add together.
Keyboard and screen reader behavior
Anchor links are native links, so keyboard users can reach them with Tab and activate them with Enter. Two details need attention.
First, sections are not focusable by default. After a jump, no focus ring appears on the target. Browsers still move the sequential focus starting point to the target. The next Tab press goes to the first focusable element inside or after the section, not back to the navigation. Do not add tabindex="0" to every section to "fix" this. It adds extra stops for no benefit.
Second, keep the visible outline on links. The focus style from earlier chapters stays in force:
a:focus-visible {
outline: 3px solid currentColor;
outline-offset: 2px;
}:focus-visible shows the outline for keyboard focus and mostly hides it for mouse clicks. That avoids the usual reason people remove outlines.
Add a skip link
A skip link is a link at the very top of the page that jumps past the navigation to the main content. Keyboard users reach it with the first Tab press, so they do not tab through every nav item on each visit. It is the most useful anchor link on the page.
<body>
<a class="skip-link" href="#main">Skip to main content</a>
<header>
<!-- navigation -->
</header>
<main id="main" tabindex="-1">
<!-- sections -->
</main>
</body>.skip-link {
position: absolute;
top: 0;
left: 0;
padding: 0.5rem 1rem;
background: var(--color-bg);
transform: translateY(-100%);
}
.skip-link:focus {
transform: translateY(0);
}The link sits above the viewport until it receives focus, then slides into view. Do not hide it with display: none or visibility: hidden, because that removes it from the tab order. The tabindex="-1" on main makes it focusable by script and by fragment navigation without adding it to the Tab sequence. This helps in browsers that do not move focus on fragment jumps.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Link changes the URL but nothing scrolls | The `id` is misspelled or differs in case | Compare `href` and `id` character by character |
| Page jumps to the wrong section | Two elements share one `id` | Make every `id` unique |
| Heading is hidden under the header | No scroll offset | Add `scroll-margin-top` or `scroll-padding-top` |
| Smooth scroll does nothing | `scroll-behavior` is set on `body` | Move it to `html` |
| Offset is doubled | Both margin and padding properties are set | Keep one |
| Skip link never appears | It is hidden with `display: none` | Move it off-screen with `transform` instead |
| Link to `#2024-work` fails in a CSS selector | Selector starts with a digit | Use `[id="2024-work"]` or start the `id` with a letter |
Exercise
Your sticky header is 4rem tall and the section headings are cut off after a nav click. Write the CSS that fixes it for all sections that have an id, leaving 1rem of space below the header. Then say why the rule is set on the sections and not on header.
Show answer
Use section[id] { scroll-margin-top: calc(4rem + 1rem); }, or html { scroll-padding-top: 5rem; } as the alternative, but not both. The offset belongs to the scroll target, because the browser reads it from the element it is scrolling to (or from the scroll container). Setting it on header has no effect on where sections stop.
Exercise
A visitor has "reduce motion" enabled in their operating system. Write a rule so smooth scrolling applies only to visitors without that preference, and name the element you set it on.
Show answer
@media (prefers-reduced-motion: no-preference) { html { scroll-behavior: smooth; } }. It goes on the html element, because the root element is the page's scroll container.