CSS font-family property


The font-family Property in CSS

The font-family property in CSS specifies the typeface for text within an element. It allows you to control the appearance of text by setting the font that is used for rendering the content. You can specify one or more fonts as a fallback mechanism in case the preferred font is unavailable.

Values of font-family

  1. Font Name

    • Specific Font: You can set a specific font by using its name. If the font name contains spaces or special characters, it should be enclosed in quotes.
    .specific-font { font-family: "Arial", sans-serif; }
  2. Generic Font Families

    • serif: Fonts with small lines or strokes regularly attached to the end of a larger stroke in a letter or symbol within a particular font.
      .serif-font { font-family: serif; }
    • sans-serif: Fonts without the small lines or strokes attached to the end of letters.
      .sans-serif-font { font-family: sans-serif; }
    • monospace: Fonts where each character takes up the same amount of horizontal space.
      .monospace-font { font-family: monospace; }
    • cursive: Fonts that resemble handwriting.
      .cursive-font { font-family: cursive; }
    • fantasy: Fonts designed to be decorative or whimsical.
      .fantasy-font { font-family: fantasy; }
  3. Fallback Fonts

    • You can provide a list of fonts as fallbacks. The browser will use the first available font in the list.
    .fallback-font { font-family: "Helvetica Neue", Arial, sans-serif; }

Syntax

font-family: "Primary Font", "Fallback Font", generic-family;

Examples

  1. Single Font Family

    .single-font { font-family: "Times New Roman", serif; }
  2. Multiple Font Families with Fallbacks

    .multiple-fonts { font-family: "Roboto", "Helvetica Neue", Arial, sans-serif; }
  3. Generic Font Family

    .generic-font { font-family: serif; }

Explanation

  • Primary Font: The font you prefer for the element. It can be a specific font like "Arial" or "Times New Roman".
  • Fallback Fonts: Additional fonts that the browser will use if the primary font is not available. These are listed in order of preference.
  • Generic Font Family: A broad category of fonts that the browser will use if none of the specified fonts are available.

Use Cases

  • Consistency: Ensure text appears in the desired typeface across different browsers and devices.
  • Fallback Mechanism: Provide fallback fonts to improve text readability if the primary font is not available.
  • Design: Enhance the visual design of a website by choosing appropriate fonts that match the overall style and theme.