CSS Web Fonts
CSS Web Fonts allow you to use custom fonts on your web pages. These fonts are loaded from a web server, enabling you to use a wide variety of fonts without relying on system-installed fonts.
Key Topics
Basic Web Font Usage
The @font-face
rule lets you define a custom font by specifying the font name and its location. Once defined, you can use it like any other font in CSS.
<style>
@font-face {
font-family: 'CustomFont';
src: url('custom-font.woff2') format('woff2');
}
.custom-font {
font-family: 'CustomFont', sans-serif;
font-size: 24px;
margin: 20px;
}
</style>
<p class="custom-font">This text uses a custom web font.</p>
Explanation: The @font-face
rule specifies a custom font named CustomFont
, loaded from the provided URL, and applied to the text.
Using Google Fonts
Google Fonts is a free library of web fonts that you can include directly in your projects. Simply link to the font in your HTML or import it in your CSS.
<head>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
</head>
<style>
.google-font {
font-family: 'Roboto', sans-serif;
font-size: 24px;
margin: 20px;
}
</style>
<p class="google-font">This text uses the Google Font Roboto.</p>
Explanation: The Roboto
font is imported from Google Fonts and applied to the text using the font-family
property.
Self-Hosted Fonts
Self-hosting fonts involves downloading font files and hosting them on your own server. This gives you more control over performance and availability.
<style>
@font-face {
font-family: 'LocalFont';
src: url('fonts/local-font.woff2') format('woff2');
}
.local-font {
font-family: 'LocalFont', serif;
font-size: 24px;
margin: 20px;
}
</style>
<p class="local-font">This text uses a self-hosted font.</p>
Explanation: The LocalFont
is self-hosted, loaded from a local directory, and applied to the text using the font-family
property.
Font Format Support
Different browsers support different font formats. Common formats include .woff
, .woff2
, .ttf
, and .otf
. Always provide multiple formats for maximum compatibility.
<style>
@font-face {
font-family: 'CompatibleFont';
src: url('compatible-font.woff2') format('woff2'),
url('compatible-font.woff') format('woff');
}
.compatible-font {
font-family: 'CompatibleFont', sans-serif;
font-size: 24px;
margin: 20px;
}
</style>
<p class="compatible-font">This text uses a font with multiple formats for compatibility.</p>
Explanation: The font is provided in both .woff2
and .woff
formats to ensure it works across different browsers.
Key Takeaways
- Web Fonts: Use
@font-face
to define custom fonts. - Google Fonts: Easily integrate fonts using links or imports.
- Self-Hosted Fonts: Download and host fonts on your own server for better control.
- Font Format Support: Provide multiple formats to ensure compatibility across browsers.
- Performance: Optimize font loading for faster web page performance.