Using the font-face rule in HTML & CSS

You aren’t just limited to using web-safe fonts such as Times or Arial on your web pages. You can choose from a range of fonts available online or even make your own font. Using the @font-face rule in CSS code, you can specify a name for a font you’d like to use on your web pages and then link to that font file.

In this tutorial, we will look at how to include fonts that you have downloaded (there are heaps of websites where you can download fonts from) on your website and also how to use fonts from Google Fonts.

The example below shows the use of two different fonts, Baloo 2 for the heading, and Roboto for the paragraph.

examplefonts

Watch the video below to see how you can use fonts like these or your own fonts in your website.

Here is some sample code which references a file called theme.css (external stylesheet), as well as fonts from Google Fonts:

<html>
    <head>
        <title>Font-face rule example</title>
        <link rel="stylesheet" href="theme.css" type="text/css"/>
        <link href="https://fonts.googleapis.com/css?family=Baloo+2|Roboto&display=swap" rel="stylesheet">
    </head>

    <body>
        <h1>This is a heading.</h1>
        <p>This is a paragraph.</p>
    </body>
</html>

And here is the theme.css file:

@font-face{
    font-family: Blackbird;
    src: url(fonts/Blackbird.ttf);
}

h1{
    font-family: 'Baloo 2', cursive;
}

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