How to use Google fonts in CSS?
It is an important aspect of any web design to choose the right font for the webpage. The use of Google fonts is advantageous because we get elegant fonts for our website. The Google fonts API makes it easier and quicker for everyone to use web-fonts. These fonts have been tested on various browser configurations.
There are two steps to start using the Google font API that are as follows:
- First, we have to add a stylesheet link for requesting the desired web font.
- Then we can style an element with the desired web font, either in a stylesheet or by inline style.
It is to be noted that when specifying a web font in CSS style, we should always mention at least one fallback web-safe font for avoiding unexpected behaviors. We can add the generic font name such as sans-serif or serif to the end of the list so that the browser will use it as the default font when required.
We can import the font family from the web font service such as Google fonts. It is to be placed in the <style> tag.
How to specify styles and font-families in a stylesheet URL
To see the list of fonts, click on the following link:
We have to start with the Google fonts API based URL to determine the URL used in our style sheet link.
Then we require to add the family= URL parameter, using one or more than one family name and styles.
For example, suppose we need to request the Roboto font, then it can be done as follows:
Note: If there is any space in the font family name, replace it with a plus sign (+).
Suppose, we have to request the font, Open Sans; then it can be written as follows:
For requesting multiple font families, the names should be separate from the pipe (|) character. For example –
Let’s understand the use of Google fonts in CSS by using some examples.
Example – Using @import rule
In this example, we are using the font family name Chelsea Market where there is a space, so we are replacing this space with the plus (+) sign.
In this example, we are using the multiple font family names that are separated by the pipe (|) character.