Embedding a font into CSS, but the font does not show up in html file

239 views Asked by At

A bit confused on the process here, but I've tried to embed a new font into a CSS file for an html website, but no matter what I try, the font does not appear on the html site. I've put the font through a converter and then put that entire file into my CSS folder that is in the same file as my index.html, to no avail. Here is the code I've put into CSS:

    font-family: 'Montserrat';
    src: url('Montserrat-SemiBold.woff2') format('woff2'),
        url('Montserrat-SemiBold.woff') format('woff'),
        url('Montserrat-SemiBold.ttf') format('truetype');
    font-weight: 600;
    font-style: normal;
    font-display: swap;

Is there anything I can try to get the code to display properly?

2

There are 2 answers

2
MAH On

You should add the @font-face keyword to import a font See this example

2
Ezra Siton On

Start here: https://www.w3schools.com/cssref/css3_pr_font-face_rule.asp

hello world example

enter image description here

You should add a CSS selector (select element(s)) body for example:

<!DOCTYPE HTML>

<html>

<head>
    <style>
        @font-face {
            font-family: 'hello-font';
            font-weight: 600;
            /* Use chrome inspect and check if the path is correct */
            src: url(hello-font.woff2) format('woff2');
        }
        /* missing in your styles */
        body {
            font-family: 'hello-font', sans-serif;
        }
    </style>
    <title>Your Website</title>
</head>

<body>
    <h1>hello world</h1>
</body>

</html>

"file not found"

Anyway if you use local files - no way to know if the path/filename is correct without live URL (Chrome inspect for red errors) - Error example:

enter image description here

Option 2 (Better) - Load google fonts by CDN

** Better speed performance / Easier to maintain.

<html>
  <head>
    <link rel="stylesheet"
          href="https://fonts.googleapis.com/css?family=Tangerine">
    <style>
      body {
        font-family: 'Tangerine', serif;
        font-size: 48px;
      }
    </style>
  </head>
  <body>
    <div>Making the Web Beautiful!</div>
  </body>
</html>