Lesson 26 of 55 · HTML
Web Fonts – Google Fonts & @font-face
Duration: 9 min
Adding Custom Fonts
Google Fonts (external)
<link href='https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap' rel='stylesheet' />
body { font-family: 'Roboto', sans-serif; }
Self‑hosted fonts (@font-face)
@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; /* Show fallback while font loads */
}
body { font-family: 'MyFont', serif; }
Performance considerations
- Preconnect to
fonts.gstatic.comfor faster Google Font loading:
<link rel='preconnect' href='https://fonts.gstatic.com' crossorigin>
font-display: swapshows a fallback font while the custom font loads, preventing flash of invisible text (FOIT).- Serve only the character subsets you need (e.g.,
latin,cyrillic) to reduce download size. - When self‑hosting, compress fonts and use
woff2as the primary format.
Quick checklist for fonts
- Font loaded via
<link>or@font-face? ✅ font-displayset toswaporfallback? ✅- Fallback font stack defined (
font-family: 'MyFont', Arial, sans-serif;)? ✅ - Preconnect added for external font providers? ✅
- Unused character subsets removed? ✅
Tip: Use the Font‑source Chrome extension to see which fonts are being downloaded and their sizes.