Previous Page
Next Page

Changing Fonts with CSS

One of the best-known abilities of CSS is that of being able to change fonts throughout a page by changing one rule. In other words, you can change the display of all of the text assigned to a class simply by changing the class's definition. In Script 11.4, adding font information to the body rule causes the entire page to display as you like it, as shown in Figure 11.4.

Script 11.4. Note the differences to the body selector compared to Script 11.2.

body {
     background-color: white;
     color: black;
     font-family: "Trebuchet MS", verdana, helvetica, arial, sans-serif;
     font-size: 0.9em;
}
img {
     margin-right: 10px;
}
.character {
     font-weight: bold;
     text-transform: uppercase;
}
div.character {
     margin: 1.5em 0em 1em 17em;
}
.directions {
     font-style: italic;
}
.dialog, .directions {
     margin-left: 22em;
}

Figure 11.4. Changing the body selector changed the font and font size on the whole page.


To change fonts with CSS:

  • body {
      background-color: white;
      color: black;
      font-family: "Trebuchet MS", verdana, helvetica, arial, sans-serif;
      font-size: 0.9em;
    }
    

    We've added two attributes to the body selector: font-family and font-size. The former, like the old <font> tag, takes a list of fonts, and the browser displays the first one it has available, going through the list from left to right. The last font given is the generic font sans-serif, which tells the browser (if this feature is supported) that if it can't find any of the listed fonts, to use any sans-serif font as a fallback. The font-size attribute, in this case, is set to display all the text at 0.9 em.

Tip

  • The first font in the list has to have quotes around it because it has a multiword name. That's true of all fonts, not just the first in a list.



Previous Page
Next Page