Skip to main content

Web Fonts and @font-face in CSS Typography

Web fonts enable you to use custom fonts on your web pages, giving you more design flexibility and control. In this tutorial, you will learn about web fonts, the @font-face rule, and how to use them in your CSS to style text with custom fonts, along with sample code and simple explanations.

What are web fonts?

Web fonts are font files that can be downloaded and used on web pages, allowing you to use a wide variety of typefaces beyond the default system fonts.

The @font-face rule

The @font-face rule is used to define a custom font and make it available for use on your web pages.

Example:

CSS
@font-face {
font-family: 'MyCustomFont';
src: url('MyCustomFont.woff2') format('woff2'), url('MyCustomFont.woff') format('woff');
}

In this example, the @font-face rule defines a custom font called "MyCustomFont" and specifies the URL for the font files in WOFF2 and WOFF formats. The format() function is used to specify the format of the font file.

Using custom fonts with font-family

After defining a custom font using the @font-face rule, you can use the font-family property to apply the custom font to an element.

CSS
body {
font-family: 'MyCustomFont', Arial, sans-serif;
}

In this example, the font-family property is set to use the custom font "MyCustomFont" if available, falling back to Arial and sans-serif if the custom font fails to load.

Cross-browser compatibility

To ensure that your custom fonts work across different browsers, it's essential to provide font files in multiple formats, such as WOFF2, WOFF, TTF, and EOT.

Conclusion

By understanding and using web fonts and the @font-face rule in CSS, you can style text with custom fonts and create unique, visually appealing web pages. This allows you to expand your design options and improve the overall user experience, making your web pages more engaging and accessible to a wider audience.