🌱BeginnerLinks
Anchor Links and Same-Page Navigation
Create table-of-contents links and page jumps using fragment identifiers and id attributes.
Overview
Anchor links (also called fragment links or in-page links) navigate to a specific section within the current page or another page without a full page reload.
The mechanism is simple:
1. Give the target element an id: <h2 id="installation">
2. Link to it with a hash: <a href="#installation">Jump to Installation</a>
This is how tables of contents, "Back to top" buttons, single-page navigation, and jump links in long documentation pages work.
Key Points
- •The href="#id" notation scrolls the page to the element with that id
- •The target element can be any element with an id h2, section, div, p
- •Anchor links can cross pages: href="/docs/guide#installation"
- •href="#" scrolls to the top of the page (or reloads if already at top)
- •Use CSS scroll-behavior: smooth for animated scrolling
- •The :target CSS pseudo-class styles the currently-targeted section
Examples
Table of contents with anchor links
<!-- Table of contents -->
<nav>
<h2>Contents</h2>
<ol>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#installation">Installation</a></li>
<li><a href="#usage">Usage</a></li>
</ol>
</nav>
<!-- Corresponding sections -->
<section id="introduction">
<h2>Introduction</h2>
<p>...</p>
</section>
<section id="installation">
<h2>Installation</h2>
<p>...</p>
</section>
<section id="usage">
<h2>Usage</h2>
<p>...</p>
</section>Back to top link
<!-- At the top of the page -->
<a id="top"><!-- Empty anchor at the top --></a>
<!-- ...lots of content... -->
<!-- At the bottom -->
<a href="#top">↑ Back to top</a>Alternatively, link to any element already at the top, like the <header id="site-header">.
Smooth scrolling and :target styling
<style>
/* Smooth scrolling for the whole page */
html { scroll-behavior: smooth; }
/* Highlight the targeted section */
section:target {
outline: 3px solid blue;
background: lightyellow;
}
</style>Cross-page anchor link
<!-- On any page links to the FAQ section of the about page -->
<a href="/about#faq">See our FAQ</a>
<!-- On the about page -->
<section id="faq">
<h2>Frequently Asked Questions</h2>
...
</section>Common Mistakes
- Using duplicate id values only one element will be targeted when the fragment fires
- Forgetting scroll-behavior: smooth page jumps abruptly by default
- Using href="#" as a placeholder for unimplemented links in production
Note
For long documentation or article pages, always add a table of contents with anchor links. It dramatically improves usability readers can jump directly to what they need.
Exercises
Write HTML to solve each exercise. Use Preview to see it render in a live iframe, then mark as done.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4