HTML and CSS

Applying Font Families to Text

With an idea of what you can reasonably choose from, it's time to go ahead and apply font families to your text. To do this, you select the text in question, and then use the font-family property and an associated value.

The value you use for the font-family property can be a single font name, a font family keyword, or a series of names followed by a font family keyword.

Single Font Names

Choose this technique only when you are absolutely certain that your audience has the font in question.

body {font-family: Arial;}

This sets the default font for all documents to Arial. The problem with this technique is that if the user doesn't have Arial installed on his or her machine, the browser will use the default fontthis is typically Times and might be quite a different look than what you're after.

Font Family Keywords

Font family keywords in CSS match the family names described in the last section: serif, sans-serif, monospace, fantasy, and cursive.

h1 {font-family: fantasy;}

This would apply the default fantasy font on your visitor's machine to all h1 headers. The problem with using keywords is that you have no control over which font that will be. As a result, keywords are typically used as a fallback method. So, if you're choosing a single font name, you can also add the related keyword after the font you've chosen:

h1 {font-family: Arial, sans-serif;}

In the fairly unlikely event that Arial isn't installed on your user's machine, it defaults to a sans-serif font on the user's machine.

Multiple Names

A technique that affords more control is using multiple family names. This means choosing fonts from the same family used in a specific order:

body {font-family: Arial, Helvetica, Verdana, sans-serif;}

The browser will look for the first named font; if it doesn't exist, it will apply the second, or third. Additionally, you'll note that I've added the family keyword name.

In Example 9-1, I've created a style sheet to demonstrate using the font-family property.

Example 9-1. Applying fonts to page elements
body {font-family: Georgia, Times, serif;}
h1, h2 {font-family: Arial, Helvetica, sans-serif;}

You'll notice that I've declared a font for the body but not the paragraphs. This provides a default for all text that falls into the body of a document.

In this example, the paragraphs simply inherit the font family from the body element. Notice also that I've grouped the h1 and h2 because I want them to have the same font. Figure 9-2 shows the results.

Figure 9-2. A sans-serif is used for the headers, with a serif font chosen for the body.

Of course, I haven't defined any other sizes or styles just yet. As a result, the browser styles are applied, so the default size for h1, h2, and paragraphs is determined by my browser until I create additional rules to control those styles.