CodeBlanks Logo Icon CodeBlanks

In-page links

HTML course · Beginner · Lesson 20/68

Learn to link to sections within the same page.

How do in-page jumps work?

To jump to headings within a long page you use an in-page link. First the target element gets an id attribute, which must be unique on the page. The link's href then starts with # and carries the same id name: href="#section-2".

When the link is clicked, the browser scrolls the matching element into view. This makes quick navigation possible inside a long document.

Jump from a link to a section

After defining an id, you write <a href="#section-2"> to jump to that section on the same page. The # sign marks a fragment, and the name after it is the target id.

The link text should describe the target, such as 'Go to the second section'. The browser only scrolls, without reloading the page, so in-page jumps are fast.

Exercise Add an in-page menu to a museum site.

The skeleton has three section headings. Add three links at the top that jump to each section: #collection, #visit and #contact. Choose your own anchor text.

Show example solution
<h1>Pera Museum</h1>
<a href="#collection">Collection</a>
<a href="#visit">Visit</a>
<a href="#contact">Contact</a>
<h2 id="collection">Collection</h2>
<p>About the exhibit.</p>
<h2 id="visit">Visit</h2>
<p>Hours.</p>
<h2 id="contact">Contact</h2>
<p>Address.</p>

In-page links recap

An in-page jump is built from two pieces: a unique id on the target element, and an href of the form #id on the link. Because the browser scrolls without reloading, navigation is fast.

In long documents a table of contents or a 'back to top' link is built this way. The next lesson shows how to control where a link opens.

Test yourself

  1. Add an id to the heading.

    <h2 id="____">Second section</h2>
    Show answer
    <h2 id="section-2">Second section</h2>
  2. Match the in-page link parts.

    id
    Name of the target element
    #
    Fragment sign
    href
    Link address
    fragment
    Part after # in the address
  3. What should href be to return to the top of the page?

    • href="top"
    • href="#top"
    • href="up"
    • href="#"
    Show answer

    href="#" — Correct. A lone # sign takes you to the top of the page.

All lessons in Beginner