When you want to set what font is used to display text you set the font-family property. The value for the font-family property is a comma separated list of fonts. Here is an example:
body { font-family: Helvetica, sans-serif; }
Font Stack
The list of fonts in the value for font-family is often referred to as the font stack. When the browser sees the font-family property, it will start to try each font listed in the font stack in order from left to right. If the font is found then the browser will stop and display the font. This is why you always end the font stack list with one of the five generic fonts.
Generic Fonts
The generic font family names represent major types of fonts. These are the types as defined by CSS. You may see print designers and books list other types of fonts. Here is a list of them. ALWAYS use these names exactly as they are listed here.
- serif
- sans-serif
- monospace
- cursive
- fantasy
Each browser and OS has a font defined for the five generics so that is guaranteed to display. What font will show will vary. For the first three you can expect:
- serif: Times New Roman or similar
- sans-serif: Arial on Windows and Helvetica on macOS
- monospace: Courier or Courier New
For the other fonts it can vary by version of OS, browser and more. Also most browsers allow people to change the default serif, sans-serif and monospace fonts so it’s really hard to tell exactly what you will get.
system-ui
In newer browsers there is an additional generic font: system-ui. This shows whatever font the operating system uses as default. Also, Apple has used -apple-system in Safari for some reason so you put that first. To ensure it works on older browsers, still use sans-serif as a generic fallback after.
body{ font-family: -apple-system, system-ui, sans-serif; }
Fonts with a space in the Name
If you font name has a space then put it in quotes.
body{ font-family: "My Font Name", serif; }
System Fonts
These are the fonts installed on the computer the person viewing your site is using. Most OS’s come with a set of system fonts and then users can install more.
Web Fonts
These are fonts that can be loaded in on the web. The ability to do this came with CSS 3. For more information on using Google web fonts see the Using Google Web Fonts post and for a list of web fonts see the Web Fonts post.
Resources
- List of Fonts found on Windows and macoS: https://www.cssfontstack.com/
- Mozilla Developer Network, font-family: https://developer.mozilla.org/en-US/docs/Web/CSS/font-family
One thought on “Using the Font-family CSS Property”