Tuesday, September 4, 2012

Internal Anchors

Anyone doing even the most basic HTML coding has used the <A> tag to create a link to another page or document.  Many of us have also used it to link to another <A> tag further down the page, or back to the top (typically in a table of contents)  The <A> tag has many other uses and options that you may not be aware of.

The official definition of links is put forth at http://www.w3.org/TR/html401/struct/links.html by the World Wide Web Consortium (W3C).  When linking to a section of a page (sometimes called a named anchor) rather than a new page or document, the most common way is to define the target with <a name="GoHere"></a> and then point your link to <a href="#GoHere">Link</a> which would scroll the page up or down to wherever the target is.  From a different page, you would create the link as <a href="Destination.html#GoHere">Link</a> or <a href="http://www.otherserver.com/Destination.html#GoHere">Link</a>.  This is the format that the W3C uses in their own documentation, such as http://www.w3.org/TR/html401/struct/links.html#h-12.2.3, and by far the most common way of defining an internal anchor.  One small line in the W3C's definition allows for other options which many people are not aware of - and this is the tidbit I want to point out, which can save time and simplify your code.
The id attribute may be used to create an anchor at the start tag of any element (including the A element).
Using this format, you can link directly to any element that has an ID assigned to it.  Since it is a very common thing to have an ID assigned to other elements such as DIV, TABLE, H1 and so on for applying CSS styles, there is no need to add an extra A tag to define the target (<a name="GoHere"></a>)  All you need to do is point your link at the already existing ID, like this:

No comments:

Post a Comment