HTML and CSS

Creating a Linked Style Sheet

To truly tap into the power of CSS, you'll be using linked style sheets the majority of the time. A linked style sheet is a separate text file into which you place all your CSS rules (but not any HTML) and is named using the .css suffix. You then link any HTML file you want to have affected by that style sheet to the sheet using the link element in the head portion of the document.

Example 7-2 shows a style sheet ready for linking. In it, I've provided a range of style rules and then saved the file to my local folder, naming the file styles.css.

Example 7-2. A style sheet ready for linking
body {
          background-color: #999;
          color: black;
          }
h1 {
          font-family: Verdana;
          font-size: 24px;
          color: #ccc;
          }
p {
          font-family: Georgia;
          font-size: 12px;
          color: white;
}

In Example 7-3, you'll find the complete HTML along with the required link to the style sheet within the same directory.

Example 7-3. The HTML for the style sheet
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>working with style</title>

<link rel="stylesheet" type="text/css" href="styles.css" media="all" />

</head>
<body>

<h1>Welcome!</h1>
<p>Paragraph one.</p>

<p>Paragraph two.</p>

</body>
</html>

The results can be seen in Figure 7-4.

Figure 7-4. Results from a linked style sheet.

Of course, you can link as many documents you want to this style sheet using the link element.

You'll note several attributes in use with the link element, as follows:

  • rel This is the relationship attribute, and it describes the relationship of the link. In this case, the relationship is with a primary style sheet, so the stylesheet value is given.

  • type As with the style element in embedded styles, you must define the type of language and format in usein this case, text/css.

  • HRef This is the familiar reference attribute. In this case, I've identified only the file because both documents are in the same directory. You might want to put your style sheets into a different directory; just be sure your href info is accurate. You can also use absolute linking to directly link to a style sheet.

  • media The media attribute enables you to define different styles for different media. If you wanted to create a separate style sheet for this document that's for handheld devices only, you would link to that and use the media="handheld" attribute. Similarly, a media="print" attribute would send that style sheet only to print. In this case, the media is defined as screen. The default is all, so if you want the same styles to apply to all media, you can use that or simply leave out the media attribute.

As mentioned, you can link as many style sheets to the same document as you want.