Which Property Is Used to Change the Font of an Element in CSS?

Typography plays a vital role in web design — from readability to aesthetics, the choice of font can dramatically impact how users experience your site. In CSS, the property used to change the font of an element is:

font-family

The font-family Property

The font-family property in CSS specifies the typeface (font) to be used for the text content of an element. This allows you to control how text appears across your website or application.

Syntax:

selector {
  font-family: "Font Name", fallback-font, generic-family;
}

Example:

h1 {
  font-family: "Georgia", "Times New Roman", serif;
}

This will try to apply the Georgia font first. If unavailable, it will use Times New Roman, and if that fails too, a default serif font.


Why Use a Font Stack?

Not every device has the same fonts installed, so it’s good practice to provide fallback options. A font stack is a prioritized list of fonts:

body {
  font-family: "Open Sans", Arial, sans-serif;
}

If "Open Sans" isn’t available, the browser falls back to Arial, then to a generic sans-serif font.


Using Web Fonts

To use custom fonts like Google Fonts:

1. Import the font in HTML:

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

2. Apply it in your CSS:

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

Other Related Font Properties

  • font-size: Adjusts text size.
  • font-weight: Sets boldness.
  • font-style: Italic or normal.
  • line-height: Controls line spacing.
  • font: A shorthand property to define all of the above in one line.

Summary

To change the font of an element in CSS, use the font-family property. This gives you full control over the typography of your website, allowing for better branding, readability, and design consistency.

p {
  font-family: "Helvetica", "Arial", sans-serif;
}
Sharing Is Caring:

Leave a Comment