Which CSS Property Changes the Font of an Element?

Choosing the right font can make or break the visual appeal and readability of a website. Whether you’re aiming for elegance, boldness, or clarity, fonts help express the tone of your content. In CSS, you can change the font of any HTML element using the font-family property.

In this blog, you’ll learn what the font-family property does, how to use it effectively, and best practices for defining font stacks.


๐ŸŽฏ The CSS Property: font-family

The font-family property in CSS is used to specify the typeface (font) of an HTML element.

โœ… Basic Syntax:

selector {
  font-family: "Font Name", fallback-font, generic-family;
}
  • selector: The element to which the style applies (e.g., p, h1, .title)
  • "Font Name": The preferred font
  • fallback-font: Optional secondary fonts
  • generic-family: A generic fallback like serif, sans-serif, or monospace

๐Ÿงพ Example:

HTML:

<p class="custom-text">This text uses a custom font.</p>

CSS:

.custom-text {
  font-family: "Georgia", "Times New Roman", serif;
}

In this example:

  • The browser first tries Georgia.
  • If unavailable, it tries Times New Roman.
  • If both fail, it defaults to a generic serif font.

๐ŸŒ Using Web Fonts (e.g., Google Fonts)

To use a custom web font like Roboto, you can import it from Google Fonts:

Step 1: Add the font link in <head>:

<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">

Step 2: Apply it with CSS:

body {
  font-family: 'Roboto', sans-serif;
}

๐Ÿ’ก Common Generic Font Families

Generic FamilyDescription
serifFonts with decorative strokes (e.g., Times New Roman)
sans-serifClean, modern fonts without strokes (e.g., Arial)
monospaceEach letter takes equal space (e.g., Courier)
cursiveScript-style fonts
fantasyDecorative or playful fonts

๐Ÿง  Tips for Using font-family

  • Always specify fallback fonts to ensure consistent appearance across devices.
  • Use quotation marks if the font name has spaces (e.g., "Open Sans").
  • Pair fonts with care โ€” balance readability and aesthetics.

๐Ÿงพ Complete Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Font Example</title>
  <link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">
  <style>
    body {
      font-family: 'Open Sans', Arial, sans-serif;
    }
  </style>
</head>
<body>

  <p>This text is styled with the 'Open Sans' font.</p>

</body>
</html>

๐Ÿ“Œ Conclusion

The CSS property used to change the font of an element is:

font-family

It allows you to specify both custom fonts and fallback options, giving you complete control over your websiteโ€™s typography.

Sharing Is Caring:

Leave a Comment