CSS `font-family`: Selecting and Styling Typefaces for Web Design

Master font selection and styling in CSS using the `font-family` property. This tutorial covers specifying font names, using generic font families, and incorporating web fonts, providing techniques for enhancing the readability and visual appeal of your web page text.



Styling Fonts with CSS `font-family`

Understanding `font-family`

The CSS `font-family` property specifies the typeface for text within an element. Choosing the right font significantly impacts a webpage's readability and visual appeal. You can specify fonts using their names, generic font families, or web fonts.

Specifying Font Families

1. Font Family Name

Specify a font by its name (e.g., "Arial", "Times New Roman"). If the specified font isn't available on the user's system, the browser will use a default font.

Example CSS

p {
  font-family: Arial;
}

2. Font Stacks

To provide fallback fonts, list several font names separated by commas. The browser will use the first available font in the list. For example:

Example CSS

p {
  font-family: 'Times New Roman', Times, serif;
}

3. Generic Font Families

Generic font families provide a category of fonts rather than a specific font. These are useful as fallback options.

  • serif: Fonts with serifs (small decorative flourishes at the ends of letter strokes).
  • sans-serif: Fonts without serifs.
  • monospace: Fonts with a fixed width for each character.
  • cursive: Script-like fonts.
  • fantasy: Decorative or artistic fonts.

4. Web Fonts

Web fonts allow you to use custom fonts from online providers (like Google Fonts). You need to include the font using the `@font-face` rule and then reference that font by its name in the `font-family` property. This allows you to use fonts that are not installed by default on a user's computer.

Example CSS (Web Font)

@font-face {
  font-family: 'MyWebFont';
  src: url('my-web-font.woff2') format('woff2');
}

p {
  font-family: 'MyWebFont', sans-serif;
}

5. System Fonts

You can use system fonts (fonts installed on the user's operating system) by specifying their names. These often provide a consistent look for users across platforms.

Example CSS (System Fonts)

p {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

Font Categories

Fonts are categorized into these types, each with distinctive characteristics:

  • Serif: Classic fonts with decorative flourishes on letter strokes.
  • Sans-serif: Modern fonts without serifs, often used for screen displays.
  • Monospaced: Each character occupies the same width (used for code and tables).
  • Cursive: Script-like fonts that mimic handwriting.
  • Fantasy: Decorative and artistic fonts.