How to Set the font of a text in CSS

CSS (Cascading Style Sheets) is a styling language used to describe the presentation of documents written in HTML and XML.

One of the most common use cases for CSS is to change the font of text on a website.

In this CSS tutorial, we’ll go over the different ways to set the font of text using CSS, including code examples to help you implement them on your own website.


Setting the font using the “font-family” property

The “font-family” property is used to set the font of text in CSS.

The property takes a list of font names as its value, with the browser using the first available font in the list.

For example, the following CSS code sets the font of all “p” elements to “Arial”:

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

In this example, the browser will first try to use the “Arial” font, but if it’s not available it will fall back to the generic “sans-serif” font.

It’s important to note that different computers and devices may have different fonts installed, so it’s a good idea to include multiple font options in the “font-family” property.

Setting the font using the “@font-face” rule

Another way to set the font of text in CSS is to use the “@font-face” rule.

This rule allows you to specify a custom font that you’ve uploaded to your server, and use it on your website.

For example, the following CSS code sets a custom font named “MyFont” as the font for all “p” elements:

@font-face {
  font-family: MyFont;
  src: url('MyFont.ttf');
}

p {
  font-family: MyFont;
}

In this example, the “MyFont.ttf” file must be located in the same directory as your CSS file.

It’s important to note that different browsers support different font file formats, so it’s a good idea to include multiple font formats in the “src” property to ensure maximum compatibility.

Setting the font using a web font service

A third way to set the font of text in CSS is to use a web font service, such as Google Fonts or Adobe Fonts.

These services allow you to use a wide variety of fonts on your website, without having to upload them to your server.

For example, to use the “Open Sans” font from Google Fonts, you would first have to include the following link in the head of your HTML file:

<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet'>

Then you can set the font-family in CSS

p {
  font-family: 'Open Sans', sans-serif;
}

This will make sure that the “Open Sans” font is loaded from Google’s servers and used on your website.

In conclusion, there are several ways to set the font of text using CSS.

The “font-family” property is the most basic way and allows you to specify a list of fonts to use, the “@font-face” rule allows you to use a custom font that you’ve uploaded to your server and web font service like Google Fonts allows you to use a wide variety of fonts on your website without having to upload them to your server.