How to link to a section of the page
Short answer
Give the section an id attribute and put it after a hash in the link:
<nav><a href="#prices">Prices</a> · <a href="#contacts">Contacts</a></nav>
<p style="height: 200px;">Long text…</p>
<h2 id="prices">Prices</h2>
<p style="height: 200px;">Tea — $3</p>
<h2 id="contacts">Contacts</h2>
<p>hello@example.com</p>A section on another page is linked the same way: href="/about#team". A link href="#" without a name leads to the very top of the page — that is how a "Back to top" button is made.
What the id should be
An id value is unique on the page: two elements with the same id break the jump. Write it in Latin letters, without spaces, after the meaning of the section — prices, delivery-terms. Such a link appears in the address bar and is easy to share: the page opens right at the needed place.
Smooth scrolling
scroll-behavior: smooth on html replaces the sharp jump with smooth scrolling:
html { scroll-behavior: smooth; }Highlighting the chosen section
The :target pseudo-class highlights the element the link led to:
<style>
:target { background: lightyellow; }
</style>
<a href="#note">Show the note</a>
<p id="note">This paragraph is highlighted after the click.</p>Common mistake
On a site with a fixed header, the section heading hides under it after the jump. Give the sections a scroll margin equal to the header height:
h2[id] { scroll-margin-top: 80px; }Functions used in this recipe
- id — A unique identifier of an element on the page.
- href — The address an `<a>` link leads to or a `<link>` points at.
- scroll-behavior — Whether jumps to anchors and scrolling from code happen instantly or smoothly.
- scroll-margin — Extra space kept around an element when the page scrolls to it — so it does not end up under a fixed header.
- :target — Matches the element whose `id` equals the fragment in the address after `#`.