The Book of CSS3 - A Developer\'s Guide to the Future of Web Design (2nd edition)

(C. Jardin) #1

48 Chapter 5


The CSS Fonts Module Level 3 (http://www.w3.org/TR/css3-fonts/) has
Candidate Recommendation status, and most of the spec has already been
implemented in modern browsers (with a couple of exceptions, which I’ll
cover later), so you can consider these features safe to use.

The @font-face Rule


To display web fonts on your pages, you first need to define them by using
the @font-face rule. This rule sets the name and type of the font and pro-
vides the browser with the location of the file to use. Here’s the basic syntax:

@font-face {
 font-family: FontName;
 src: local('fontname'), xurl('/path/filename.otf') yformat('opentype');
}

I’ll break this syntax down a little. First, I give the font a name with the
font-family property (). This property is one you should be familiar with,
although it serves a slightly different purpose inside the rule than it does
when used in the declaration block for a regular selector; here, it’s used to
declare a font name, not to refer to one. Just like the font-family property in
CSS2.1, you can use multiple, space-separated words as long as you enclose
them within single quotation marks.

noTe When you define your font’s name with font-family, you can use the same name
multiple times—in fact, sometimes you need to. I’ll discuss why shortly, in “Defining
Different Faces” on page 49.

Next is the src property (), which tells the browser the location of
the font file. This property accepts a few different values: local () uses the
name of the source font to check if the font is already installed on the user’s
machine; and url (x) provides a path to the font if it’s not available locally.
I’ve also included the optional format (y) hint, used to specify the font type;
in this example, I used OpenType, but more types are available, and I’ll dis-
cuss those later in “Font Formats” on page 52.
I can supply many different values for the src property by separating
the values with commas, as I’ve done in the code example. This utilizes the
power of the cascade to allow different fall-back values, which will come in
handy in a later example.

noTe Remember that in a font stack the browser will use the first file it encounters that can
be loaded, rather than reading through all files and choosing the most recent.

To use the font I just defined, I need only call its name in the font stack,
as I’d normally do:

E { font-family: FontName; }
Free download pdf