OneBite.Dev - Coding blog in a bite size

import google font into css

Code snippet for how to import google font into css with sample and detail explanation

Google Fonts is a popular font platform that allows you to incorporate a wide range of unique, aesthetic fonts onto your projects. This simple guide will walk you through how to import a Google Font into your CSS styling sheet.

Importing Google Font Into CSS

The first step to importing a Google Font into your CSS is to head to the Google Fonts website. Browse through and select a font that complements the aesthetic of your project. For the sake of this tutorial, we’ll be using the font ‘Roboto’.

Here’s how it’s done:

@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');

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

Code Explanation for Importing Google Font Into CSS

Let’s break down the steps involved in incorporating Google Fonts into your CSS.

  1. First Line- @import statement: The @import statement allows you to import styles from other style sheets. In this case, we are importing the ‘Roboto’ font from Google Fonts. The URL in the parentheses is the link to the Google Font stylesheet for the ‘Roboto’ font.

  2. Second Section- Applying the font: The font-family CSS property sets the font for an element. Here, we’ve set the ‘Roboto’ font for the body of our HTML. This means that the ‘Roboto’ font will be applied to all the text within the body tags of our HTML document. The sans-serif is the fallback font, in case the ‘Roboto’ font fails to load for any reason.

Remember, Google Fonts are not always the fastest option because they need to be imported from the Google server. Hence, it’s always good practice to have a fallback font.

Also note that the semi-colon (;) plays a critical role. Without it, the browser would not be able to read the CSS properly and it may cause some errors.

You have now learned how to import a Google font into your CSS styling sheet. Happy coding!

css