Sub topic 4
Linking to a section of a page
This chapter assumes you can write an a element with an href, and that you know how relative and absolute URLs work from the earlier chapters.
How fragment links work
A fragment is the part of a URL that starts with #. When a link's href is #install, the browser looks in the current page for the element whose id is install and scrolls to it. The browser doesn't reload the page, and the address bar gains #install.
<nav>
<a href="#install">Jump to Installation</a>
</nav>
<h2 id="install">Installation</h2>
<p>Steps go here.</p>The link and its target need no other connection. The only requirement is that the href after the # matches an id exactly.
Rules for ids
- An
idmust be unique in the page. If two elements share one, the browser uses the first. - An
idcan't contain spaces. Use hyphens, such asid="getting-started". - Matching is case-sensitive.
#Installwill not findid="install". - Put the
idon the element you want the visitor to see first, usually a heading.
Linking to a section of another page
Add the fragment after the page URL. The browser loads that page and then scrolls to the element.
<a href="/docs/setup.html#install">Installation steps</a>
<a href="https://example.com/faq.html#billing">Billing questions</a>Back to the top
A link to # alone, or to #top, scrolls to the top of the page. The #top form works because browsers treat that name as the start of the document, even when no element has that id.
<a href="#top">Back to top</a>Common errors
- A typo does nothing. If the
iddoesn't match, the browser doesn't show an error. The page just doesn't move. Check the spelling and case on both sides. - A duplicate id. Copying a section and forgetting to change its
idsends links to the wrong place. - A fixed header covers the target. The heading scrolls to the top edge and hides behind a sticky header. Fix it in CSS with
scroll-margin-topon the target. - Using the old
nameattribute. Old pages used<a name="install">. Useidon any element instead.
Exercise
A page has <h2 id="Pricing">Pricing</h2>, and a link reads <a href="#pricing">See prices</a>. The link does nothing. Why, and how do you fix it?
Show answer
Fragment matching is case-sensitive, so #pricing doesn't match id="Pricing". Make both use the same case, preferably lowercase: id="pricing" and href="#pricing".