To create links to sections on the same page, or from outside pages linking in, its recommended that you use unique IDs. You can also use named anchors, but this is not recommended since it bloats your markup.
Unique IDs are assigned to elements using the ID Attribute of HTML, this attribute can be used both for scripting purposes, as well as linking purposes.
The first example shows how to link to subsections using IDs, the next, named anchors.
A common scenario where you would want to link to subsections, is if you got a contents list somewhere on the page, which briefly lists the sections.
<!DOCTYPE html> <html lang="en-US"> <head> <title>Linking to subsections with IDs</title> </head> <body> <h1 id="Sec0">How to link Subsections on a page</h1> <p>This is the main section on a page, followed by a subsection which we will link to using a unique ID. Such IDs can be assigned on the server-side, using preg_match_all (or equlivant).</p> <p><a href="#Sec1">Link to Subsection</a></p> <h2 id="Sec1" style="margin-top:1024px;">The subsection</h2> <p>You might not be able to notice the difference in larger resolutions, try to make the browser window smaller, and than click the link in the first section.</p> </body> </html>
Named anchors are also valid, but they appear rather clumsy when compared to simply throwing in a unique ID on the section/element of relevance.
Instead of using the ID attribute, you simply need to throw in a anchor with a name attribute, just after the section that you want to link to.
<!DOCTYPE html> <html lang="en-US"> <head> <title>Using named anchors to link to subsections</title> </head> <body> <h1 id="Sec0">Using named anchors to link to subsections</h1> <p>Named anchors are more clumsy than simply using IDs, which is why Brugbart recommends that you stick with IDs, unless you got specific reason to using named anchors.</p> <p><a href="#Sec1">Link to Subsection</a></p> <h2 style="margin-top:1024px;">The subsection</h2> <p><a name="Sec1"></a>In larger resolutions this may be hard to spot, so try re-sizing your browser window, in case nothing appears to happen when you click the link.</p> </body> </html>
Additional information about this subject.