Font loading in CSS is one of the important issues that has a significant impact on the appearance and readability of websites. Choosing and using an appropriate font can positively affect user experience and the attractiveness of the website. In this section, we will discuss different topics regarding how to load and use fonts on websites.
In the programming community, using beautiful and attractive fonts has always been a point of attention. For example, using Google Fonts is one of the preferred methods for improving the appearance of websites. Therefore, for the effective use of fonts, we should also understand their loading techniques.
One way to efficiently load fonts is to use techniques such as lazy loading and preloading. These techniques allow you to make sure that fonts are loaded only when necessary or are more readily available at hand.
Below is an example code for font loading via CSS. Additionally, line-by-line explanations of the code will also be provided for better understanding.
<style>
@font-face {
font-family: 'MyCustomFont';
src: url('my-custom-font.woff2') format('woff2'),
url('my-custom-font.woff') format('woff');
font-weight: normal;
font-style: normal;
font-display: swap;
}
body {
font-family: 'MyCustomFont', sans-serif;
}
</style>
Code Explanations
@font-face
: This rule allows a custom font to be added to the website. font-family
: A name assigned to this font that can be used for reference in CSS. src
: The paths to the font files that can be in different formats such as woff2 and woff. font-weight
and font-style
: Specify the weight and style of the font which can be normal, bold, etc. font-display
: A property that defines how the font will be displayed during loading, such as swap which uses a temporary font during loading. body
: Here, the custom font defined is applied to the entire body of the webpage.