How to use Google Fonts in HTML and CSS (Step-by-Step with Code)

Choosing the right typography is crucial for making your website look modern and professional. Google Fonts is a free and popular library that offers thousands of beautiful web fonts. In this guide, we will show you exactly how to use Google Fonts in HTML and CSS using a few simple steps.

In this tutorial, we will learn how to properly link and use Google Fonts in your HTML and CSS files, and we will also cover a common mistake that breaks font loading.

Step 1: Get the Font Link from Google Fonts

Go to the official Google Fonts Website.

Search for your favorite font (e.g., Roboto or Poppins).Select the font styles you want (e.g., Regular 400, Bold 700).

Click on the Selected Families icon in the top right corner.

Copy the HTML <link> codes provided under the “Embed” section.

Step 2: Paste the Code into HTML

To use the font, you must link it inside the <head> section of your HTML document.

Here is the 100% correct, verified code snippet. You can copy this code and use it directly:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Google Fonts Integration Example</title>
    
    <!-- Corrected Links to import Google Fonts (Roboto) -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
    
    <style>
        /* Applying the Google Font to the entire webpage */
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f4f4f9;
            color: #333;
            text-align: center;
            padding: 50px;
        }
        h1 {
            color: #2c3e50;
        }
    </style>
</head>
<body>

    <h1>Hello World! This text is using Google Fonts.</h1>
    <p>This is a live example of integrating custom fonts into HTML and CSS.</p>

</body>
</html>

⚠️ Common Mistake to Avoid (Why your font isn’t loading)

Many developers make a small typo when writing or copying the preconnect links manually, which stops the fonts from loading. Always double-check your URLs

Wrong URL: https://googleapis.com ❌

Correct URL: https://fonts.googleapis.com ✅

Wrong URL: https://gstatic.com ❌

Correct URL: https://fonts.gstatic.com ✅

Missing the fonts. prefix is the biggest reason behind broken custom fonts.

Step 3: Apply Font Family in CSS

Once the font is linked in the HTML head, you can apply it to any element in your CSS using the font-family property

css

h1 {
    font-family: 'Roboto', sans-serif;
    font-weight: 700;
}

1 thought on “How to use Google Fonts in HTML and CSS (Step-by-Step with Code)”

Leave a Comment