Connect with us

CSS

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

Spread the love

Typography plays a key role in web design—setting the tone, improving readability, and enhancing user experience. When you want to change the font of text in an HTML element using CSS, there’s one property you’ll reach for most often.

👉 The CSS property used to change the font is: font-family

Let’s explore how it works, with examples and tips for best practices.


✅ The font-family Property

The font-family property specifies the typeface (font) used for the content of an HTML element.

📌 Basic Syntax:

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

This allows you to assign a primary font and define fallback options in case the browser can’t load the preferred one.


✅ Example 1: Change Font for a Paragraph

p {
  font-family: Arial, sans-serif;
}

This sets the paragraph text to Arial. If Arial isn’t available, it falls back to a generic sans-serif font.


✅ Example 2: Change Font for Headings

h1, h2, h3 {
  font-family: 'Georgia', serif;
}

This applies the elegant Georgia font to all headings, with serif as a backup.


✅ Example 3: Using Web Fonts (e.g., Google Fonts)

You can link to external fonts for more style flexibility:

📌 HTML:

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

📌 CSS:

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

This applies Roboto across your website.


✅ Shorthand Option: font

CSS also provides the font shorthand property to set multiple font-related styles in one line:

p {
  font: italic 16px/1.5 'Open Sans', sans-serif;
}

This sets:

  • Font style: italic
  • Font size: 16px
  • Line height: 1.5
  • Font family: 'Open Sans', sans-serif

⚠️ When using font shorthand, font-size and font-family are required.


🧾 Summary

PurposeCSS PropertyExample
Change font of textfont-familyfont-family: Arial, sans-serif;
Use multiple fallbacksfont-familyfont-family: 'Roboto', Arial, sans-serif;
Set full font style at oncefont (shorthand)font: italic 14px 'Georgia', serif;

🧠 Conclusion

To change the font of an HTML element using CSS, use the font-family property. Whether you’re using system fonts or importing web fonts, font-family gives you the control to make your design clean, readable, and consistent.


Pro Tip: Always include at least one generic font family (like sans-serif, serif, or monospace) to ensure graceful degradation across devices.


Spread the love
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *