How to use custom fonts in CSS Using @font-face

We often want to style text on our web pages. We normally use Web Safe fonts to style texts. But sometimes we may need to use custom fonts to style texts in our web application. Using CSS @font-face rule, we can define our own fonts in CSS.

We need to define a font name for the font and must provide the path to the font file. The value of font-family property is the font name and the value of src is the path to the font file location. We can later refer to this custom font by using its font name.

@font-face {
    font-family: Roboto;
    src: url(/assets/Roboto-regular.ttf);
}
p {
    font-family: Roboto;
    font-size: 15px;
}

We can use multiple variations of the font with same by defining some of the font properties like font-style, font-weight, font-stretch etc.

For example:

If we want to define a custom font for light, regular and bold fonts, then we can define three fonts with the same name and we can specify different font-weight properties for the fonts. And later by mentioning the respective font-weight property, we can set fonts accordingly.

@font-face {
     font-family: Roboto;
     src: url(/assets/Roboto-regular.ttf);
     font-weight: 400;
}

@font-face {
    font-family: Roboto;
    src: url(/assets/Roboto-light.ttf);
    font-weight: 100;
}

@font-face {
    font-family: Roboto;
    src: url(/assets/Roboto-bold.ttf);
    font-weight: 600;
}

p {
    font-family: Roboto;
    font-weight: 400;
    font-size: 15px;
}

label {
    font-family: Roboto;
    font-weight: 600;
}

So now explore new fonts in your application with @font-face and style your texts the way you want.

Leave a Reply

Your email address will not be published. Required fields are marked *