CSS font-family
The CSS font-family
property is used to define the font family or typeface of the text within an element. It allows you to specify a list of font families that the browser should use to display the text, ordered by priority. If the first font is not available, the browser will attempt to use the next one in the list, and so on.
The syntax for using the font-family
property is as follows:
selector {
font-family: font1, font2, font3, ...;
}
selector
: Represents the CSS class, ID, or element selector of the element to which the font family will be applied.font1
,font2
,font3
, etc.: Represents the font families you want to set. These can be the names of specific fonts or generic font families.
Examples:
p {
font-family: "Helvetica Neue", Arial, sans-serif;
}
h1 {
font-family: "Times New Roman", Times, serif;
}
span {
font-family: "Courier New", monospace;
}
In the above examples:
- All
<p>
elements will attempt to use the font “Helvetica Neue.” If that font is not available, the browser will fall back to “Arial.” If both “Helvetica Neue” and “Arial” are not available, the browser will use the default sans-serif font for the user’s system. - All
<h1>
elements will attempt to use the font “Times New Roman.” If that font is not available, the browser will fall back to “Times.” If both “Times New Roman” and “Times” are not available, the browser will use the default serif font for the user’s system. - All
<span>
elements will attempt to use the font “Courier New.” If that font is not available, the browser will use the default monospace font for the user’s system.
When specifying font family names that consist of multiple words or include spaces, enclose them in double or single quotes to ensure they are interpreted correctly.
Using multiple font families in the font-family
property is important for cross-browser compatibility and ensuring that your text is displayed with an appropriate font, even if the user doesn’t have the specific font you initially preferred.
It’s essential to choose font families that match the overall style and tone of your website, keeping in mind readability and accessibility. Additionally, consider using fallback generic font families like serif
, sans-serif
, monospace
, cursive
, and fantasy
as the last option in your font-family
list, as they represent generic font styles available on most systems.