Aug 312014
Article HTML

If the amount of content in a web page is large, its readability can be improved structuring the content in sections and subsections. In this case, a Table of contents (TOC) is an element that can improve substantially the usability of the page.

This post goes through the steps involved in adding a TOC to a web page.

Structuring the content of the page with headings <h1>…<h6>

In HTML language, elements <h1> to <h6> can be used to tag the headings of the sections in the document, in a hierarchy of up to six levels. For instance, a page that talks about programming languages could be structured as:

Browsers usually display the texts inside these tags using a font size bigger than that used for other texts in the document. Besides, almost all web pages load a CSS stylesheet that specifies additional characteristics such as the font type, font color or background color for each of these elements.

Adding anchors to the section headings

Our goal is to create and place at the top of the page a table of contents with entries that link to the sections in the document. To be able to link to a given section from the TOC entry, we must add first to the heading of the section a HTML “anchor”

In HTML, an anchor is added using the same tag used to create links. But, instead of a “href” attribute with the destination url, anchors have and “id” attribute with a unique identifier as value.

After adding anchors to the headings, the document in the above sample might look like this:

Creating manually the table of contents

After the sections in the document have been tagged with anchors, the table of contents, with entries linking to the sections can be created. To add style, ordered or un-ordered lists (<ol>, <ul>) can be used in the TOC:

As we can see, the value of the href attribute in the links in the table of contents is just the name of the anchor, prefixed with a “#” symbol.

This syntax can also be used if the destination anchor is in a page different from the page where the TOC is placed. For instance, if the chapter “The PHP language” is in a page with url “/programming-languages-page-2”, the link in the TOC pointing to that chapter could be written as:

 Posted by at 10:14 am

 Leave a Reply