Naming a Fragment

HTML provides two ways to identify a document fragment: by inserting an anchor (a) element with the name attribute (instead of href) or by adding the id attribute to any HTML element. Both methods act as a marker that can be referenced from a link later.

XHTML documents must use the id attribute for all fragment identifiers in order to be well-structured XML. Unfortunately, the id attribute is not universally supported by all browsers for this purpose (support is lacking in Version 4 browsers). To ensure maximum backward and forward compatibility, the XHTML Recommendation suggests redundant markup using both id and name in the a element.

In this example, a named anchor is used to let users link directly to a “Stock Quotes” section of a web document called dailynews.html. First, the heading is marked up as a named anchor with the name “stocks.” Named anchors receive no special style treatment by default (in other words, they are not underlined like anchors with the href attribute).

<h1><a name="stocks" id="stocks">Daily Stock Quotes</a></h1>

The same fragment might also be identified right in the h1 element as shown here (if Version 4 browsers don’t need to be supported).

<h1id="stocks">Daily Stock Quotes<h1>

The value of the name and id attributes must be unique within the document (in other words, two elements can’t be given the same name).

Get Web Design in a Nutshell, 3rd Edition 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.