Lesson 7

Using External and Internal Links

What You’ll Learn in This Lesson:

  • Image How to use anchor links

  • Image How to link between pages on your own site

  • Image How to link to external content

  • Image How to link to non-Web documents such as PDF and Word documents

  • Image How to link to an email address

  • Image How to use window targeting with your links

  • Image How to style your links with CSS

  • Image How to add descriptions to links

  • Image Best practices for web page links

So far, you have learned how to use HTML tags to create some basic web pages. However, at this point, those pieces of content are islands unto themselves, with no connection to anything else. To turn your work into real web content, you need to connect it to the rest of the Web—or at least to other pages within your own sites.

This lesson shows you how to create hypertext links to content within your own document and how to link to other external documents. In addition, you will learn how to style hypertext links so that they display in the color and decoration you desire—not necessarily the default blue underlined display. You will also learn some of the best practices that designers have learned from over 20 years of linking web pages.

Using Web Addresses

The simplest way to store web content for an individual website is to place all the files in the same folder. When files are stored together like this, you can link to them by simply providing the name of the file in the href attribute of the <a> tag.

Note

Before you get too far into this lesson, you might want a refresher on the basics of where to put files on your server and how to manage files within a set of directories. This information is important to understand when creating links in web content. Refer to Lesson 1, “Understanding How the Web Works,” specifically the section titled “Understanding Where to Place Files on the Web Server.”

An attribute is a piece of information associated with a tag that provides further details about the tag. For example, the href attribute of the <a> tag identifies the address of the page or document to which you are linking.

When you have more than a few pages, or when you start to have an organization structure to the content in your site, you should put your files into directories (or folders, if you will) whose names reflect the content within them. For example, all your images could be in an images directory, corporate information could be in an about directory, and so on. Regardless of how you organize your documents within your own web server, you can use relative addresses, which include only enough information to find one page from another.

A relative address describes the path from one web page to another, as opposed to a full (or absolute) Internet address.

As you recall from Lesson 1, the document root of your web server is the directory designated as the top-level directory for your web content. In web addresses, that document root is represented by the forward slash (/). All subsequent levels of directories are separated by the same type of forward slash, as in this example: /directory/subdirectory/subsubdirectory/.

Caution

The forward slash (/) is always used to separate directories in HTML. Don’t use the backslash (), which is normally used in the Windows operating system, to separate your directories. You can remember this by thinking that everything on the web moves forward, so use forward slashes.

Suppose you are creating a page named zoo.html in your document root, and you want to include a link to pages named african.html and asian.html in the elephants subdirectory. The links would look like the following:

<a href="/elephants/african.html">Learn about African elephants.</a>
<a href="/elephants/asian.html">Learn about Asian elephants.</a>

These specific addresses are actually called relative-root addresses, in that they are relative addresses that lack the entire domain name, but they are specifically relative to the document root specified by the forward slash.

Using a regular relative address, you can skip the initial forward slash. This type of address allows the links to become relative to whatever directory they are in—whether that is the document root or another directory one or more levels down from the document root. This is what a regular relative address looks like:

<a href="elephants/african.html">Learn about African elephants.</a>
<a href="elephants/asian.html">Learn about Asian elephants.</a>

Your african.html and asian.html documents in the elephants subdirectory could link back to the main zoo.html page in either of these ways:

<a href="http://www.yourdomain.com/zoo.html">Return to the zoo.</a>
<a href="/zoo.html">Return to the zoo.</a>
<a href="../zoo.html">Return to the zoo.</a>

The first link is an absolute link. With an absolute link, there is absolutely no doubt where the link should go because the full URL is provided—domain name included.

The second link is a relative-root link. It is relative to the domain you are currently browsing and, therefore, does not require the protocol type (for example, http://) or domain name (for example, www.yourdomain.com); the initial forward slash is provided to show that the address begins at the document root.

Note

The general rule surrounding relative addressing (elephants/african.html) versus absolute addressing (http://www.takeme2thezoo.com/elephants/african.html) is that you should use relative addressing when linking to files that are stored together, such as files that are all part of the same website. Use absolute addressing when you’re linking to files somewhere else—another computer, another disk drive, or, more commonly, another website on the Internet.

In the third link, the double dot (..) is a special command that indicates the folder that contains the current folder—in other words, the parent folder. Anytime you see the double dot, just think to yourself, “Go up a level in the directory structure.”

The advantage of relative addressing is that the links will work as long as the pages remain on the same site. If you use relative addressing consistently throughout your web pages, you can move directories of pages to another folder, disk drive, or web server without changing the links.

Relative addresses can span quite complex directory structures, if necessary. Lesson 28, “Organizing and Managing a Website,” offers more detailed advice for organizing and linking large numbers of web pages.

Linking Within a Page Using Anchors

The <a> tag—the tag responsible for hyperlinks on the web—got its name from the word anchor, because a link serves as a designation for a spot in a web page. In examples throughout these lessons so far, you’ve learned how to use the <a> tag to link to somewhere else, but that’s only half its usefulness. Let’s get started working with anchor links that link to content within the same page.

Identifying Locations in a Page with Anchors

The <a> tag can be used to mark a spot on a page as an anchor, enabling you to create a link that points to that exact spot. Listing 7.1, presented a bit later in this lesson, demonstrates a link to an anchor within a page. To see how such links are made, let’s take a quick peek ahead at the first <h1> tag in the listing:

<h1 id="top">First Lines of Shakespearean Sonnets</h1>

The <a> tag uses the href attribute to specify a hyperlinked target. The <a href> is what you click, and the element with the corresponding id attribute is where you go when you click there. In this example, the <h1> tag is specifying a target, but it is also the headline for that section of the page. The id attribute gives a name, in this case top, to the specific point on the page where the tag occurs. A unique name must be assigned to the id attribute, but it can be placed on any element in the page where you want the link to land.

Note

You can use an id attribute on any container element in HTML5, and you can use the <a> tag to point to those elements as anchor links as well. Best practices recommend that you not add extra tags to your document but simply add the id attribute to relevant tags that are already present.

Linking to Anchor Locations

Listing 7.1 shows a site with various anchor points placed throughout a single page. Take a look at the last <a> tag in Listing 7.1 to see an example:

<a href="#top">Return to Index.</a>

The # symbol means that the word top refers to a named anchor point within the current document rather than to a separate page. When a user clicks Return to Index, the web browser displays the part of the page starting with the tag with the id="top" attribute.

Listing 7.1 Setting Anchor Points by Using the <a> Tag with an id Attribute

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Alphabetical Shakespeare</title>
  </head>
  <body>
    <article>
      <header>
        <h1 id="top">First Lines of Shakespearean Sonnets</h1>
      </header>
      <p>Don't you just hate when you go a-courting, and you're
      down on one knee about to rattle off a totally romantic
      Shakespearean sonnet, and zap! You space it. <em>"Um... It
      was, uh... I think it started with a B..."</em></p>
      <p>Well, appearest thou no longer the dork. Simply refer to
      this page, click on the first letter of the sonnet you want,
      and get an instant reminder of the first line to get you
      started. <em>"Beshrew that heart that makes my heart to
      groan..."</em></p>

      <p style="text-align:center"><strong>Alphabetical Index</strong></p>
      <div style="text-align:center">
        <a href="#A">A</a> <a href="#B">B</a> <a href="#C">C</a>
        <a href="#D">D</a> <a href="#E">E</a> <a href="#F">F</a>
        <a href="#G">G</a> <a href="#H">H</a> <a href="#I">I</a>
        <a href="#J">J</a> <a href="#K">K</a> <a href="#L">L</a>
        <a href="#M">M</a> <a href="#N">N</a> <a href="#O">O</a>
        <a href="#P">P</a> <a href="#Q">Q</a> <a href="#R">R</a>
        <a href="#S">S</a> <a href="#T">T</a> <a href="#U">U</a>
        <a href="#V">V</a> <a href="#W">W</a> <a href="#X">X</a>
        <a href="#Y">Y</a> <a href="#Z">Z</a>
      </div>
      <hr>

      <section>
        <header>
          <h1 id="A">A</h1>
        </header>
        <ul>
          <li>A woman's face with nature's own hand painted,</li>
          <li>Accuse me thus, that I have scanted all, </li>
          <li>Against my love shall be as I am now</li>
          <li>Against that time (if ever that time come) </li>
          <li>Ah wherefore with infection should he live, </li>
          <li>Alack what poverty my muse brings forth, </li>
          <li>Alas 'tis true, I have gone here and there, </li>
          <li>As a decrepit father takes delight, </li>
          <li>As an unperfect actor on the stage, </li>
          <li>As fast as thou shalt wane so fast thou grow'st, </li>
        </ul>
        <p><a href="#top">Return to Index.</a></p>
      </section>
      <hr>
<!-- continue with the alphabet -->
      <section>
        <header>
          <h1 id="Z">Z</h1>
        </header>
        <p>(No sonnets start with Z.)</p>
        <p><a href="#top"><em>Return to Index.</em></a></p>
      </section>
    </article>
  </body>
</html>

Note

Near the end of Listing 7.1 you see the following line:

<!-- continue with the alphabet -->

This text (an HTML comment) will appear in your source code but will not be displayed by the browser. You will learn more about commenting your code in Lesson 28.

Each of the <a href> links in Listing 7.1 makes an underlined link leading to a corresponding <a id> anchor—or it would if all the text were filled in. Only A and Z will work in this example because only the A and Z links have corresponding text to link to, but feel free to fill in the rest on your own! Clicking the letter Z under Alphabetical Index in Figure 7.1, for example, takes you to the part of the page shown in Figure 7.2.

A screenshot shows the output of "Alphabetical Shakespeare" file, where the sonnets are grouped alphabetically with an Alphabetical index at the top. The index is comprised of alphabets A to Z, all clickable links.
Figure 7.1 The <h1 id> tags in Listing 7.1 don’t appear differently from standard <h1> tags. The <a href> tags appear as underlined links.
A screenshot shows the output of clicking "Z" from the Alphabetical index. It shows the section containing "Z" sonnets. It is also indicated that all groups have a "Return to Index" link and are divided by horizontal lines at the end.
Figure 7.2 Clicking the letter Z on the page shown in Figure 7.1 takes you to the appropriate section of the same page.

Note

In HTML4, anchor names specified via the id attribute in a tag have to start with a letter. But HTML5 is less strict. The ID must contain at least one character and no space characters. Best practices suggest that it’s best to avoid characters that have meaning in HTML, CSS, JavaScript, and HTTP (the protocol that web servers use to load pages). These include periods (.), colons (:), semicolons (;) pound signs (#), slashes (/), and backslashes (). We recommend using only numbers and letters from a standard keyboard in your id attributes.

Having mastered the concept of linking to sections of text within a single page, you will now learn to link other pieces of web content.

Linking Between Your Own Web Content

As you learned earlier in this lesson, you do not need to include http:// before each address specified in the href attribute when linking to content within your domain (or on the same computer, if you are viewing your site locally). When you create a link from one file to another file within the same domain or on the same computer, you don’t need to specify a complete Internet address. In fact, if the two files are stored in the same folder, you can simply use the name of the HTML file by itself:

<a href="pagetwo.html">Go to Page 2.</a>

For example, Listing 7.2 and Figure 7.3 show a quiz page with a link to the answers page shown in Listing 7.3 and Figure 7.4. The answers page contains a link back to the quiz page. Because the page in Listing 7.2 links to another page in the same directory, the filename can be used in place of a complete address.

Listing 7.2 The historyanswers.html File

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>History Quiz</title>
  </head>
 <body>
    <section>
      <header>
        <h1>History Quiz</h1>
      </header>
      <p>Complete the following rhymes. (Example: William the
      Conqueror played cruel tricks on the Saxons in... ten
      sixty-six.)</p>
      <ol>
        <li>Columbus sailed the ocean blue in...</li>
        <li>The Spanish Armada met its fate in...</li>
        <li>London burnt like rotten sticks in...</li>
      </ol>
      <p style="text-align: center;">
        <a href="historyanswers.html">Check Your Answers!</a>
      </p>
    </section>
  </body>
</html>

A screenshot shows the output of "History Quiz" file. The page displays a main question followed by three sub-questions numbered 1, 2, and 3. It has a "Check your answers" link at the bottom.
Figure 7.3 This is the historyquiz.html file listed in Listing 7.2 and referred to by the link in Listing 7.3.

Listing 7.3 The historyanswers.html File That historyquiz.html Links To

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>History Quiz Answers</title>
  </head>
 <body>
    <section>
      <header>
        <h1>History Quiz Answers</h1>
      </header>
      <ol>
        <li>...fourteen hundred and ninety-two.</li>
        <li>...fifteen hundred and eighty-eight.</li>
        <li>...sixteen hundred and sixty-six.</li>
      </ol>
      <p style="text-align: center;">
        <a href="historyquiz.html">Return to the Questions</a>
      </p>
    </section>
  </body>
</html>

A screenshot shows the "History Quiz Answers" page that displays the answers, similarly numbered 1 through 3, for the history quizzes with "Return to the questions" link at the bottom.
Figure 7.4 The Check Your Answers! link in Figure 7.3 takes you to this answers page. The Return to the Questions link takes you back to what’s shown in Figure 7.3.

Using filenames instead of complete Internet addresses saves you a lot of typing. More importantly, the links between your pages will work properly no matter where the group of pages is stored. You can test the links while the files are still on your computer’s hard drive. You can then move them to a web server, a CD-ROM, a DVD, or a USB drive, and all the links will still work correctly. There is nothing magic about this simplified approach to identifying web pages; it all has to do with web page addressing, as you’ve already learned.

Note

In both Listing 7.2 and Listing 7.3, you’ll see the use of the <section></section> tag pair around the bulk of the content. You might wonder whether that is entirely necessary—after all, it is the only content on the page. The answer is, no, it isn’t entirely necessary. The HTML would validate just fine, and no one looking at this code would be confused by its organization if the <section></section> tags were not present. The tags are used here just to make sure you get used to seeing them throughout these code examples and to provide an opportunity to include this note about how you might use the <section></section> tags at some point in the future. For example, if you were to put both the questions section and the answers section on one page and apply styles and a little bit of JavaScript-based interactivity, you could hide one section (the questions) until the reader clicked a link that would then show the other section (the answers). This action is beyond the scope of these lessons, but it is an example of how the simplest bit of markup can set you up for bigger things later.

Linking to Non-HTML Files

Once you know how to link to an HTML document, you can link to non-HTML documents in the same way. Items like word processing documents and PDF files are examples of other files on the web. To link to them, you just replace the URL in the href attribute with the location of the document, as in these examples:

<a href="myWordDoc.doc">my word-processed document</a>
<a href="myPDFfile.pdf">my PDF file</a>

The first example links to a word processing document (.doc), and the second example links to a PDF file (.pdf). When these links are clicked, the browser will do one of two things: It will either open the document in the window or it will open a download dialog box that asks the user to download the file.

Sometimes it makes sense to require that a linked document be downloaded to the user’s local computer. But web browsers typically try to display as much as they can without downloading, as downloading can be slow, and some operating systems don’t allow it. In order to force the browser to open a download dialog box, add the attribute download to the link. This is what’s called a Boolean attribute because it is either on or off. Sometimes you will see them written as having self-referential values, such as download="download". This attribute is new in HTML5 and has good support in all modern browsers except Internet Explorer (but it works in Edge) and iOS Safari.

To force the previous two links to be download links, write the following:

<a href="myWordDoc.doc" download>my word-processed document</a>
<a href="myPDFfile.pdf" download>my PDF file</a>

Linking to External Web Content

The only difference between linking to pages within your own site and linking to external web content is that when linking outside your site, you need to include the full address to that bit of content. The full address includes the http:// or https:// before the domain name and then the full pathname to the file (for example, an HTML file, an image file, a multimedia file, and so on). This is called the fully qualified domain name (FQDN).

For example, to include a link to Google from within one of your own web pages, you would use this type of absolute addressing in your <a> link:

<a href="https://www.google.com/">Go to Google</a>

Note

These days, it is more common to see web pages with https:// as the protocol for the web page URL. This is because more and more servers are using secure SSL certificates to keep their websites secure. You will learn more about this in Lesson 27, “Working with Web-Based Forms.”

Caution

As you might know, you can leave out the protocol (http:// or https://) at the front of any address when typing it into most web browsers. However, you cannot leave out that part when you type an Internet address into an <a href> link on a web page.

You can apply what you have learned in previous sections to creating links to named anchors on other pages. Linked anchors are not limited to the same page. You can link to a named anchor on another page by including the address or filename followed by # and the anchor name. For example, the following link would take you to an anchor named photos within the african.html page inside the elephants directory on the (fictional) domain www.takeme2thezoo.com:

<a href="http://www.takeme2thezoo.com/elephants/african.html#photos">
Check out the African Elephant Photos!</a>

If you are linking from another page already on the www.takeme2thezoo.com domain (because you are, in fact, the site maintainer), your link might simply be as follows:

<a href="/elephants/african.html#photos">Check out the  
African Elephant Photos!</a>

The protocol and the domain name would not be necessary in this instance, as you have already learned.

Linking to an Email Address

In addition to linking between pages and between parts of a single page, the <a> tag enables you to link to email addresses. This is the simplest way to enable your web page visitors to talk back to you. Of course, you could just provide visitors with your email address and trust them to type it into whatever email programs they use, but that increases the likelihood for errors. By providing a clickable link to your email address, you make it almost completely effortless for them to send you messages and eliminate the chance for typos.

An HTML link to an email address looks like the following:

<a href="mailto:[email protected]">Send me an
email message.</a>

The words Send me an email message will appear just like any other <a> link.

If you want people to see your actual email address (so that they can make note of it or send a message using a different email program), include it both in the href attribute and as part of the message between the <a> and </a> tags, like this:

<a href="mailto:[email protected]">[email protected]</a>

Caution

Many spammers use automated tools to harvest email addresses from web pages by looking for mailto links and email addresses. There are ways to try to hide the email address from spammers, but in general if the email address works in the web page, spammers can grab it. So be sure that whatever address you point to has a strong spam filter on it.

In most web browsers, when a user clicks the link, that person gets a window into which he or she can type a message that is immediately sent to the mailto email address—and the email program that person uses to send and receive email will automatically be used.

You can provide some additional information in the link so that the subject and body of the message also have default values. You do this by adding subject and body variables to the mailto link. You separate the variables from the email address with a question mark (?), separate the value from the variable with an equal sign (=), and then separate each of the variable and value pairs with an ampersand (&). You don’t have to understand the variable/value terminology at this point. Here is an example of specifying a subject and body for the preceding email example:

<a href="mailto:[email protected]?subject=Book Question&body=
When is the next edition coming out?">[email protected]</a>

When a user clicks this link, an email message is created with [email protected] as the recipient, Book Question as the subject of the message, and When is the next edition coming out? as the message body.

Note

If you want to specify only an email message subject and not the body, you can just leave off the ampersand and the body variable, equal sign, and value text string, as follows:

<a href = "mailto:[email protected]?subject= Book Question" > [email protected] </a>

You can add carbon-copy and blind carbon-copy recipients to the message as well with the cc and bcc properties, like so:

<a href="mailto:[email protected]?subject=
Book Question&[email protected]&
[email protected]">Mail the author</a>

This will send the Book Question message to [email protected], cc [email protected], and bcc [email protected].

Note

If you put an email contact link in the footer of all your web pages, you make it easy for others to contact you; you give them a way to tell you about any problems with the page that your testing might have missed. Use the <address> HTML tag to semantically define this email address as the address for the web page.

Opening a Link in a New Browser Window

Now that you have a handle on how to create addresses for links—both internal (within your site) and external (to other sites)—there is one additional method of linking: forcing the user to open links in new windows.

You’ve no doubt heard of pop-up windows, which are browser windows—typically advertising products or services—that are intended to be opened and displayed automatically without the user’s approval. Many modern browsers disallow this behavior. However, the concept of opening another window or targeting another location serves a valid purpose in some instances. For example, you might want to present information in a smaller secondary browser window but still allow the user to see the information in the main window. This is often the case when the user is clicking on a link to an animated demo, a movie clip, or some other multimedia element. You might also want to target a new browser window when you are linking to content offsite.

The word target is important because this is the name of the attribute used with the <a> tag. The target attribute points to a valid browsing context, or “new window to open.”

A valid HTML link that opens in a new window is constructed like so:

<a href="/some/file.html" target="_blank">Open a Window!</a>

The keyword _blank is a special target name that tells the browser to open in a new window without a name. The initial underscore (_) is not a typo but is part of the name. You can also give windows names by targeting them with any text designation, such as the following:

<a href="/some/file.html" target="newWindow">Open a New Window!</a>

In this case, the new window will be called newWindow. Any other links you target with that same name will open in that same window.

Remember that forcing a link to open in a new browser window—especially when it’s a full-size new window—goes against some principles of usability and accessibility. Best practices recommend that you avoid doing this unless you have no other choice.

Giving Titles to Links

One feature of links that many web designers forget is the title attribute. This attribute lets you add to your links descriptions that aren’t immediately visible on web pages. For example, this HTML creates a link that reads Come see my page:

<a href="myPage.html" title="This is the best page on this site">
Come see my page</a>

When people view the page, it will display as a standard link, but if they hover over or focus on the link, the browser will display the message This is the best page on this site.

Giving title to links is especially useful for people who rely on screen readers, as they can get a little more information about a link before they click on it. You can also use the title attribute as a style hook. To reference every link with a title attribute you write the following:

a[title] { /* put styles here */ }

Think of the title attribute as a way to give a little more information about a link without taking up space on the page. It’s not meant to be a repetition of the link text, as that would be pointless and boring. And it does nothing for search engine visibility, so don’t fill it with spammy keyword phrases. Use it to provide more useful information. If you don’t have any more useful information, don’t use the title attribute.

Using CSS to Style Hyperlinks

The default display of a text-based hyperlink on a web page is underlined blue text. You might also have noticed that links you have previously visited appear as underlined purple text; that color is also a default. If you’ve spent any time at all on the Web, you will also have noticed that not all links are blue or purple—and for that we are all thankful. Using a little CSS and knowledge of the various pseudo-classes for the <a> link, you can make your links look however you want.

Note

You can use graphics as links (instead of using text as links) by putting an <img> tag between the opening <a> and closing </a> tags.

A pseudo-class is a class that describes styles for elements that apply to certain circumstances, such as various states of user interaction with that element.

For example, these are the common pseudo-classes for the <a> tag:

  • Image a:link—Describes the style of a hyperlink that has not been visited previously.

  • Image a:visited—Describes the style of a hyperlink that has been visited previously and is present in the browser’s memory.

  • Image a:hover—Describes the style of a hyperlink as a user’s mouse hovers over it (and before it has been clicked).

  • Image a:focus—Describes the style of a hyperlink as the user activates the link. This is often used on devices where there is no mouse, so clicking is not possible.

  • Image a:active—Describes the style of a hyperlink that is in the act of being clicked but has not yet been released.

Note

It’s important to remember to style the :focus property because many people today use devices without mice to view web pages. Most people view web pages on tablets and smartphones more often than on computers with mice. And :focus is also important for accessibility to people who use the keyboard to navigate the web.

For example, let’s say you want to produce a link with the following styles:

  • Image A font that is bold and Verdana (and not underlined, meaning it has no text decoration)

  • Image A base color that is light blue

  • Image The color red when users hover over it, give it focus, or are clicking it

  • Image The color gray after users have visited it

Your style sheet entries might look like the following:

a {
   font-family: Verdana, sans-serif;
   font-weight: bold;
   text-decoration: none;
}
a:link {
   color: #6479A0;
}
a:visited {
   color: #cccccc;
}
a:hover {
   color: #e03a3e;
}
a:focus {
   color: #e03a3e;
}
a:active {
   color: #e03a3e;
}

Note

The colors in this example are indicated by their hexadecimal values.

Because the sample link will be Verdana bold (and not underlined), regardless of the state it is in, those three property and value pairs can reside in the rule for the a selector. However, because each pseudo-class must have a specific color associated with it, we use a rule for each pseudo-class, as shown in the code example. The pseudo-class inherits the style of the parent rule unless the rule for the pseudo-class specifically overrides that rule. In other words, all the pseudo-classes in the preceding example will be Verdana bold (and not underlined). However, if we used the following rule for the hover pseudo-class, the text would display in Comic Sans when users hover over it (if, in fact, they have the Comic Sans font installed):

a:hover {
   font-family: "Comic Sans MS";
   color: #e03a3e;
}

In addition, because the active, focus, and hover pseudo-classes use the same font color, you can combine style rules for them:

a:hover, a:focus, a:active {
   color: #e03a3e;
}

Listing 7.4 puts these code snippets together to produce a page using styled pseudo-classes; Figure 7.5 shows the results of this code.

Listing 7.4 Using Styles to Display Link Pseudo-classes

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Sample Link Style</title>
    <style>
    a {
      font-family: Verdana, sans-serif;
      font-weight: bold;
      text-decoration: none;
    }
    a:link {
      color: #6479a0;
    }
    a:visited {
       color: #cccccc;
    }
    a:hover, a:active {
       color: #ff0000;
    }
    </style>
  </head>
  <body>
    <h1>Sample Link Style</h1>
    <p><a href="simplelinkstyle.html">The first time you see me,
    I should be a light blue, bold, non-underlined link in
    the Verdana font</a>.</p>
  </body>
</html>

A screenshot shows the "Sample link style" window that displays a text in the link style with font properties: Verdana font, bold and non-underlined.
Figure 7.5 A link can use particular styles to control the visual display.

If you view the example in your web browser, indeed the link should be a light blue, bold, nonunderlined Verdana font. If you hover over the link or click the link without releasing it, it should turn red. If you click and release the link, the page simply reloads because the link points to the file with the same name. However, at that point, the link is in your browser’s memory and thus is displayed as a visited link—and it appears gray instead of blue.

You can use CSS to apply a wide range of text-related changes to your links. You can change fonts, sizes, weights, decoration, and so on. Sometimes you might want several sets of link styles in your style sheet. In that case, you can create classes; you aren’t limited to working with only one set of styles for the <a> tag. The following example is a set of style sheet rules for a footerlink class for links you might want to place in the footer area of a website:

a.footerlink {
   font-family: Verdana, sans-serif;
   font-weight: bold;
   font-size: 75%;
   text-decoration: none;
}
a.footerlink:link,
a.footerlink:visited {
   color: #6479a0;
}
a.footerlink:hover,
a.footerlink:active,
a.footerlink:focus {
   color: #e03a3e;
}

As you can see in the example that follows, the class name (footerlink) appears after the selector name (a), separated by a dot, and before the pseudo-class name (hover), separated by a colon:

selector.class:pseudo-class
a.footerlink:hover

Using Links Effectively

Throughout this lesson we’ve mentioned a few best practices for using links effectively, but there are a few more you should be aware of:

  • Image Make your links stand out—Links should stand out from the text on the page so that customers know that they can do something with them. You can make your links stand out by changing their color, changing their background color, underlining them (the default in most browsers), making their font larger, making them bold, or in other ways. The important thing is that for links to work, your users must know they are links.

  • Image For links use only link styles—This is the corollary to the first rule. If your links are to stand out, they must look different from the surrounding text. If you underline links, then you should not underline non-links. The same idea applies to link colors: If you color your links red, then you should not use red for other, non-link text.

  • Image Style visited links—It’s important to let people know when they’ve been to a page before. Users get frustrated when they end up in a loop of links because the visited links look the same as the unvisited ones. A good rule of thumb is to use a slightly darker shade of the same color you used for the standard links. This provides a visual cue that the links are visited without messing with your design.

  • Image Use descriptive content for link text—It’s tempting to write “Click here” and make just those two words the link, but such links are harder to use. There is nothing about “Click here” that says what the user will get when he or she clicks. It forces the reader to scan the rest of the content to determine whether it’s worth clicking, and the more work you make your readers do, the more likely they will be to go to someone else’s site. Note that this doesn’t mean you can’t say “Click here”; just don’t have that be the only text that is clickable.

  • Image Add padding to text links—Padding is the space surrounding links. By adding padding, you ensure that your links are more clickable, even if the words are very small. To add some padding, you could write: a { padding: 3px; }. This is especially important for navigation links. You’ll learn more about padding in Lesson 9, “Working with Margins, Padding, Alignment, and Floating.”

  • Image Link images—Usability studies have shown that people notice and click on images even when they are not links. So if you have images on your web pages, it makes sense to make them links. At a bare minimum, you should link your logo to your home page, but any other images on you pages should be linked as well.

  • Image Use icons to aid in comprehension—You can add icons to links to help people quickly see where they go. There are icons for all kinds of things, from social media to file types to entertainment and more.

  • Image Avoid tiny links—Small links are hard to click and can be nearly impossible to tap on a touchscreen device. The smaller the text, the harder it is for your readers to use. If your site targets seniors, you should use fonts for all your text of at least 12 points.

Summary

The <a> tag is what makes hypertext “hyper.” With it, you can create links between pages, as well as links to specific anchor points on any page. This lesson focused on creating and styling simple links to other pages by using either relative or absolute addressing to identify the pages.

You learned that when you’re creating links to other people’s pages, it’s important to include the full Internet address of each page in an <a href> tag. For links between your own pages, include just the filenames and enough directory information to get from one page to another.

You also learned how to create named anchor points within a page and how to create links to a specific anchor. You learned how to link to your email address so that users can easily send messages to you. You also learned how to protect your email address from spammers. Finally, you learned methods for controlling the display of your links by using CSS and some of the best practices for linking based on over 20 years of web design.

Table 7.1 summarizes the <a> tag discussed in this lesson.

Table 7.1 HTML Tags and Attributes Covered in Lesson 7

Tag/Attribute

Function

<a></a>

With the href attribute, creates a link to another document or anchor. With the id attribute, creates an anchor that can be linked to.

Attributes

Function

href="address"

Specifies the address of the document or anchor point to link to.

id="name"

Specifies the name for this anchor point in the document.

Q&A

Q. What happens if I link to a page on the Internet, and then the person who owns that page deletes or moves it?

A. It depends on how the maintainer of that external page has set up his or her web server. Usually, you will see a page not found message (sometimes called a 404 page, referencing the HTTP error code the server delivers) when you click a link that has been moved or deleted. You can still click the Back button to return to your page. As a site maintainer, you can periodically run link-checking programs to ensure that your internal and external links are valid. An example of this is the Link Checker service at https://validator.w3.org/checklink.

Q. One of the internal links on my website works fine on my computer, but when I put the pages on the Internet, the link doesn’t work anymore. What’s up?

A. These are the most likely culprits:

  • Image Capitalization problems—On Windows computers, linking to a file named MyFile.html with <a href="myfile.html"> works. On most web servers, the link must be <a href="MyFile.html"> or you must change the name of the file to myfile.html. To make matters worse, some text editors and file transfer programs actually change the capitalization without telling you. The best solution is to stick with all-lowercase filenames for web pages.

  • Image Spaces in filenames—Most web servers don’t allow filenames with spaces. For example, you should never name a web page my page.html. Instead, name it mypage.html or even my_page.html or my-page.html (using an underscore or dash instead of a space).

  • Image Local absolute addresses—If you link to a file using a local absolute address, such as C:mywebsite ews.html, the link won’t work when you place the file on the Internet. You should never use local absolute addresses; when this occurs, it is usually an accident caused by a temporary link that was created to test part of a page. So be careful to remove any test links before publishing a page on the Web.

Q. Can I put both href and id in the same <a> tag? Would I want to do this for any reason?

A. You can, and it might save you some typing if you have a named anchor point and a link right next to each other. It’s generally better, however, to use the id attribute on another element entirely to avoid confusion. Remember that they play very different roles in an HTML document.

Q. What happens if I accidentally misspell the name of an anchor or forget to put the # in front of it?

A. If you link to an anchor name that doesn’t exist within a page or if you misspell the anchor name, the link goes to the top of that page. If you write an anchor without a URL or # in front of it, the browser will attempt to take you to a page by the same name, which will usually result in a Page Not Found error.

Workshop

The Workshop contains quiz questions and exercises to help you solidify your understanding of the material covered.

Quiz

1. Your best friend from elementary school finds you on the Internet and says he wants to trade home page links. How do you put a link to his site at www.supercheapsuits.com/~billybob/ on one of your pages?

2. What HTML would you use to make it possible for someone clicking the words “About the Authors” at the top of a page to skip down to a list of credits somewhere else on the page?

3. If your email address is [email protected], how would you make the text “goodnight greeting” into a link that people can click to compose and send you an email message?

4. What attribute can you add to an HTML element to turn it into an anchor?

5. What character do you use to link to an anchor?

6. How do you tell a browser that the link target document should be downloaded rather than loaded in the window?

7. When should you include http:// in a link?

8. What mail features can you use in a mailto link?

9. When is the best case to force a link to open in a new window?

10. What pseudo-class do you use to style visited links?

Note

Just a reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.informit.com/register and register this book (using ISBN 9780672338083), you can receive free access to an online Web Edition that not only contains the complete text of this book but also features an interactive version of this quiz.

Answers

1. Put the following on your page:

<a href="http://www.supercheapsuits.com/~billybob/">Billy
Bob's site</a>

2. Type this at the top of the page:

<a href="#credits">About the Authors</a>

Type this at the beginning of the credits section:

<anytag id="credits">

3. Type the following on your web page:

Send me a <a href="mailto:[email protected]">goodnight greeting</a>!

4. The id attribute can be used on any HTML element as an anchor.

5. You use the pound sign (#) to link to a named anchor point on the page.

6. Use the attribute download to tell the browser the link target should be downloaded.

7. You should include the http:// and the rest of the FQDN when you are linking to a page outside the current site.

8. You must point to the email address the message is to. Optional values are subject, body, cc, and bcc.

9. You should avoid forcing links to open in a new window at all costs.

10. Use the a:visited pseudo-class to style visited links.

Exercises

  • Image Create an HTML file consisting of a formatted list of your favorite websites. You might already have these sites bookmarked in your web browser, in which case you can visit them to find the exact URL in the browser’s address bar.

  • Image If you have created any pages for a website, look through them and consider whether there are any places in the text where you’d like to make it easy for people to contact you. Include a link to your email address there. You can never provide too many opportunities for people to contact you and tell you what they need or what they think about your products—especially if you’re running a business.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset