How to import custom fonts to your website using @font-face in CSS

·

2 min read

How to import custom fonts to your website using @font-face in CSS

Did you know that you can use custom fonts in your website without the user having it on their computer? You can do it in two ways:

  1. Import the fonts from sources like Google Fonts, MyFonts, Adobe FF Market, etc., directly into your website, when the page loads.
  2. Create a font-family for your custom .otf/.ttf font files using @font-face and use them in your website.

The focus of this article will be on introducing you to the 2nd method.
In CSS, the @font-face rule allows you to load custom fonts using font files like True Type Fonts (.ttf) and Open Type Fonts (.otf).

For example, this is how you would use the @font-face rule to declare three different forms of a font from their respective files (.ttf format):

  • Give your custom font, a name using the font-family property in the @font-face declaration:
@font-face {
    font-family: Curve;
}

Here, I've given my custom font, the name "Curve".

  • Each form of a custom font must be declared in a @font-face rule. To declare multiple forms for the same font, give the same font-family to all of them.
  • In order to differentiate multiple forms of the same font-family, we can use different font-weight values. For example:
@font-face {
    font-family: Curve;
    src: url("curve-bold.ttf");
    font-weight: bold;
}

@font-face {
    font-family: Curve;
    src: url("curve-dashed.ttf");
    font-weight: 100;
}

I've declared two different forms for my Curve font-family, each with a different font-weight values and src values pointing to the files of the font's forms.

  • Note: You must define a name for the font (i.e., font-family) before you point to the file using the src.

Now, your custom font is all set to be used in your website.

HTML:

<p>Coding is fun!</p>
<p>Coding is fun!</p>
<p>Coding is fun</p>

In the HTML file, I have created three paragraphs.

CSS:

@font-face {
    font-family: Curve;
    src: url("curve-regular.ttf");
    font-weight: normal;
}

@font-face {
    font-family: Curve;
    src: url("curve-bold.ttf");
    font-weight: bold;
}

@font-face {
    font-family: Curve;
    src: url("curve-dashed.ttf");
    font-weight: 100;
}

p:nth-child(1) {
    font-family: Curve;
    font-weight: normal;
}

p:nth-child(2) {
    font-family: Curve;
    font-weight: bold;
}

p:nth-child(3) {
    font-family: Curve;
    font-weight: 100;
}

Here,

  • I have declared three @font-face rules for the same font-family.
  • I declared each form with a different font-weight.
  • Each form declaration has an src value pointing to its file.

Output: output.jpg

Thank you for reading!

View this blog on Medium
Feel free to connect with me on Twitter and LinkedIn
Happy Coding!

Did you find this article valuable?

Support Charan by becoming a sponsor. Any amount is appreciated!