Setting a font

Chapter 14 2 mins

Learning outcomes:

  1. Setting the font in CSS
  2. Fallback fonts

The font-family property

The font-family property is used to set the font for a given element

For instance if we want to set the font of all paragraphs to Arial we can write the following:

p {font-family: Arial}
The name of the font isn't case sensitive. You could've also written ARIAL or arial, but just to remain farily consistent go with the naming above.

Notice one thing over here that we didn't put quotes around the value Arial. When we have a font name without spaces such as Arial, Tahoma, Verdana, Lato, Roboto etc we can write it without putting quotes around it. However if it has spaces as in Segoe UI, Open Sans, Nothing You Could Do then we have to surround the value in quotes.

Example with single quotes:

p {font-family: 'Open Sans'}

Example with double quotes:

p {font-family: "Open Sans"}

Generic font families

CSS offers its users with some generic font-families to apply the system's allocated font for that family, to given elements. The generic families are as follows:

  1. sans-serif A sans-serif font
  2. serif A serif font
  3. monospace A monospace font

So instead of giving real font names you could just hang out around with some generic font families.

p {font-family: sans-serif}
The generic font families don't need to have quotes around them.
The following is wrong:
p {font-family: "sans-serif"}

Fallback fonts

Sometimes while requesting a font it is possible that for some reason the font fails to load - there is some network error or the font is unavailable on the sytem.

In such cases having a fallback font can help. To add a fallback font just add the new font's name, as discussed above, after the previous one seperated by a comma.

/* If Open Sans fails, Arial will be applied */
p {font-family: "Open Sans", Arial}

You could have as many fallback fonts you wish but it makes sense to have only a few of them - no more than three or four.

/* If Open Sans fails, Arial will be applied,
if even it fails then sans-serif generic family will take over */
p {font-family: "Open Sans", Arial, sans-serif}

If the first one fails the second one loads; if the second one fails the third one loads and so on..

However, if the first or second one loads after sometime it replaces the second one, or third one whichever is applied.

And that's all for setting fonts in CSS. Next we will see how to work with these fonts in CSS by playing around with their weights, caps, spacing and much more.

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage