OneBite.Dev - Coding blog in a bite size

use google fonts in css

Code snippet for how to use google fonts in css with sample and detail explanation

Google fonts are a versatile resource that can greatly enhance your web pages, giving them a unique and polished look. In this article, we will guide you on how to use Google fonts in CSS.

Code snippet for Google Fonts Integration

To add Google Fonts to your website, first, you need to visit fonts.google.com. Select the font you want to use and click on the “Select this Font” link. A window will popup, which contains the that you should add to your HTML file’s head section like so:

<head>
<!-- Import the Google Font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto&display=swap">
</head>

After doing this, we can now use the Google Font in our CSS file by calling it through the ‘font-family’ property. For instance, if we want to apply the font to our entire body content, our code would look something like this:

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

In this example, ‘Roboto’ is the Google Font we chose, and ‘sans-serif’ is the fallback font in case the Google Font fails to load.

Code Explanation for Google Fonts Integration

In the code snippet, we use the link tag in HTML to import the Google font ‘Roboto’ from the provided Google URL.

The href attribute specifies the location of the external resource, which in this case, is a CSS file hosted on the Google Fonts server.

The rel attribute specifies the relationship between the current document and the linked document. This means the current HTML file should look for styling information in that CSS file (i.e., the stylesheet).

Inside the CSS file, we used ‘font-family’ property which is intended to let designers use a ranked list of font family names that will be used in the sequence until a match is found.

The ‘Roboto’ font family is our first choice; however, if it can’t be loaded for some reason, the browser will try to use the generic font family ‘sans-serif’ which is our second choice.

By doing this, we have now successfully imported and implemented a Google font into our website. We can apply it to various aspects such as headers, paragraphs, divs, etc.

Explore, experiment, and play around with as many fonts as you would like to get the right impact and look for your website! Each font has the power to create a unique user experience.

css