Linking Within a Document

By default, when you link to a page, the browser displays the top of that page. To aid in navigation, you can use the anchor tag to link to a specific point or section within a document. This is a two-step process.

Naming a fragment

First, you need to identify and name the portion of the document (called a fragment) that you want to link to. The fragment is marked using the anchor (<a>) tag with its name attribute, giving the document fragment a name that can be referenced from a link.

To illustrate, let’s set up a named fragment within a sample document called dailynews.html so users can link directly to the Stock Quotes section of the page. The following anchor tag marks the Stock Quotes title as a fragment named “stocks.”

<A NAME="stocks">Daily Stock Quotes</A>

Linking to a fragment

The second step is to create a link to the fragment using a standard anchor tag with its href attribute. Fragment identifiers are placed at the end of the pathname and are preceded by the hash (#) symbol.

To link to the “stocks” fragment from within dailynews.html, the link would look like this:

<A HREF="#stocks">Check out the Stock Quotes</A>

Linking to a fragment in another document

You can create a link to a named fragment of any document on the Web by using the complete pathname. (Of course, the named anchors would have to be in place already.) To link to the stocks section from another document in the same directory, use a relative pathname as follows:

<A HREF="dailynews.html#stocks">Go ...

Get Web Design in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.