I was recently asked how to create a table of contents to link to content within the same page of a site. This is very easy to accomplish, and can help your reader more easily navigate longer content on your website.
You accomplish this by using “Named Anchors”. Named Anchors work very much like regular anchors, which link to other content. The big difference with named anchors is that, instead of linking to a full URL, they link to an ID within the same page.
Anchors and Named Anchors
Confused? Don’t worry, it’s very simple. Let’s compare these two types of anchors.
A typical anchor looks like this: <a href=”http://google.com”>Search Google</a>. All this does is make the text within the anchor, “Search Google”, a link to http://google.com.
The structure of a named anchor is the same, except that the address will be different. Here’s an example: <a href=”#top”>Back to Top</a>. The big different here is that, instead of a URL, we’re linking to #top.
Fair enough, you say, but what is #top?
Creating an ID
In HTML and CSS, the # identifies a unique ID. This can identify some element, somewhere on the page. IDs are like classes, with the big difference being that a class can be repeated multiple times within a page, while an ID must be unique. That uniqueness is what makes named anchors possible.
You could use a class to style a type of content that might appear a number of times, like an image you would like centered and surrounded with a one-pixel black border. By contrast, you might use the ID to identify an important headline in the content, such as the conclusion to an article.
You define your ID by typing id=”id-name” within the tag. For instance, <h2 id=”conclusion”>Conclusion</h2> would assign this headline with the ID of “conclusion”.
Putting it All Together
I added an ID of “anchors” to the “Anchors and Named Anchors” headline of this article. This link will jump you to it.
Here’s the code for the headline.
<h2 id=”anchors”>Anchors and Named Anchors</h2>
And here’s the code for the link.
<a title=”Jump to the anchors headline” href=”#anchors”>This link will jump you to it</a>
Taking it a Step Farther
You can also use this to link to IDs on other pages. Simply create a normal anchor link, and append the ID to the end of the link, like so <a href=”http://website.com/#uniqueid”>Jump to unique ID</a>. This is especially handy for linking into specific sections of longer pages on your site.
For a live example, here’s a link to the middle of my article on Custom Taxonomies.
Well, that’s it for setting up named anchors on a web page. I think this is a pretty useful technique to use, and something your readers will appreciate.
Have questions about any of this? Don’t be shy about posting comments.