Linking to a location on a page - A Smarter Way To Learn HTML & CSS (2015)

A Smarter Way To Learn HTML & CSS(2015)

31
Linking to a location
on a page

When you create a page of significant length, you might want to provide links to various sections of the page, so the user doesn’t have to scroll through the page looking for the section she wants to see. On a long page, it’s also nice to provide links to the top of the page, so when she’s finished with a lower section, she can jump back to the top.

You begin by choosing a heading, paragraph, or other element to serve as the starting point for the section. You give this element an id.

<h2 id="fame-claim">OUR CLAIM TO FAME</h2>

Then you create a link to it.

<a href="#fame-claim">Read all about our claim to fame.</a>

It’s like links you learned about in the last chapter, except that a # precedes the id in the reference.

To insert a link back to the top, you’d create an id for an element at or near the top of the page. It could be the main heading for the page. Or it could be the content div that encompasses all the content on the page.

<div class="content" id="top">

Then, wherever you want to place the link, you could write…

<a href="#top">Back to the top</a>

When you want to link to a location on another page on the same site, you have to include the name of the page.

<a href="faq.html#why-me">Get answers to your cosmic questions</a>

The code above links to a heading, paragraph, or other element with the id why-me on the faq.html page.

When you want to link to a section of a page on another site, you have to include the domain name.

<a href="http://www.cosmicquestions.com/faq.html#why-me">Get answers to your cosmic questions</a>

In order for this to work, the page on the other site has to have an element with the id “why-me.”

In your HTML file give the heading at the top of the page an id. At the bottom of the page code a link to that heading. Save the file and display the page. Scroll down to the link and click it.

Sample HTML code is at:
http://asmarterwaytolearn.com/htmlcss/practice-31-1.html.

Find the interactive coding exercises for this chapter at:
http://www.ASmarterWayToLearn.com/htmlcss/31.html