Can I Anchor a Div?
Anchors have long been used to link to specific parts of Web pages. An anchor consists of a hyperlink created by anchor tags and an element -- headings, paragraphs, images and divs, to name a few examples -- that contains an ID. As long as a div has an ID, it is usable as an anchor.
-
HTML Anchors
-
An HTML anchor uses the “<a>” anchor tags to link to any element by its “name” or “ID” attribute. Though “name” was used in the past, use of “ID” is considered a best practice since “name” is now a deprecated -- not current -- attribute in HTML 4 and above. Instead of creating a link that points to a file path, you can create a link pointing to any HTML element's ID or name.
Uses of Anchors
-
Anchors are typically used on Web pages that contain large amounts of text. On a Web page that has many sections with sub-headings, you can create a list of links that act as a table of contents. Each link would point to a heading tag or div by its ID. Another use of anchors is to create “jump” links that take the user back to the top of a long Web page, which reduces the need for scrolling. It is also possible to link to a specific part of another page.
-
Anchoring a Div
-
Adding an ID to a div will allow you to link to it using “<a>” tags:
<div id=”my_stuff”>
Content...
</div>The ID is now accessible by anchor tags, style sheets and JavaScript. If you have a div that already contains an ID, you will need to use that ID.
Linking to a Div Anchor
-
The method for creating a link to an anchored element involves setting the “href” attribute of a pair of “<a>” tags to the ID name, prefixed by a hash symbol:
<a href=”#my_stuff”>Go to My Stuff</a>
<a href=”page2.html#mystuff”>Go to My Stuff on Page 2</a>The first link will send the user to the element with an ID of “my_stuff,” so long as it is on the same page that is being viewed in the browser. The second link will load a different page in the browser and jump to the “my_stuff” div.
-