@font-face RuleCSS Web Fonts let you use custom fonts that are not installed on the user’s system. These fonts can be hosted on services like Google Fonts or served from your own server using the @font-face rule.
This improves branding, readability, and overall design consistency across different devices and operating systems.
<link> tag.@font-face: CSS rule used to define and load custom font files (e.g. .woff2, .woff, .ttf).WOFF2 and WOFF for better compression and browser support.font-family so text still appears even if the main font fails.font-display: Controls how text behaves while the font is loading (e.g. swap).There are two popular ways to use web fonts:
<link> tag in the <head> and then use the font via font-family.@font-face: Host font files yourself and define them with @font-face, then apply them anywhere on the page.Basic idea: First tell the browser where to find the font, then use that font name in your CSS.
Steps to use Google Fonts:
<link> tag.<head>.font-family in CSS.
<!-- Load Roboto from Google Fonts and apply it to the body -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Google Fonts Example</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Roboto', sans-serif;
}
h1 {
font-weight: 700;
}
p {
font-size: 1rem;
}
</style>
</head>
<body>
<h1>This heading uses Roboto</h1>
<p>This paragraph also uses the Roboto web font.</p>
</body>
</html>
@font-face with Local Font FilesHere we host the font files ourselves (e.g., in a fonts/ folder) and define them with @font-face. Then we use that font for headings.
/* Register a custom font using @font-face and then use it in headings */
@font-face {
font-family: 'MyFont';
src: url('fonts/MyFont.woff2') format('woff2'),
url('fonts/MyFont.woff') format('woff');
font-weight: normal;
font-style: normal;
font-display: swap;
}
body {
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
h1 {
font-family: 'MyFont', sans-serif;
font-size: 2.2rem;
}
Note: Place the font files in a proper directory like fonts/ and make sure the paths in src are correct. Including both WOFF2 and WOFF improves browser support.
Below is a visual comparison using built-in fonts (just for understanding font-family behavior):
When you replace these with a Google Font or a custom @font-face font, the layout stays the same but the overall look and feel changes to match your brand.
'MyFont', 'Segoe UI', system-ui, sans-serif.font-display: swap; in @font-face to avoid invisible text while fonts load.<p> elements on a sample page.@font-face.@font-face font.font-display: auto | swap | fallback | optional and observe how text behaves while fonts download.