Web Fonts
Overview
By default, the browser can only render text using 'System Fonts' (fonts already installed on the user's hard drive, like Arial, Times New Roman, or San Francisco on Macs). If you want your website to have a unique, branded aesthetic, you must instruct the browser to download a custom font file from a server using the @font-face rule. This is exactly how services like Google Fonts work under the hood.
Syntax
/* Importing a custom font directly into CSS */
@font-face {
/* You decide what name to call it */
font-family: 'MyCustomBrandFont';
/* Link to the file (woff2 is the most compressed, modern format) */
src: url('/fonts/brand-font-regular.woff2') format('woff2');
/* Specify the exact weight this file represents */
font-weight: 400;
/* Prevent 'invisible text' while downloading by showing a fallback immediately */
font-display: swap;
}
body {
/* Use your custom font, but ALWAYS provide safe fallbacks */
font-family: 'MyCustomBrandFont', 'Helvetica Neue', Arial, sans-serif;
}Common Pitfalls
- Forgetting the
font-display: swapproperty. Without this, if the user is on a slow 3G connection, the browser will hide all text on the website until the custom font finishes downloading (The Flash of Invisible Text - FOIT).swapforces the browser to render the text instantly using Arial, and then seamlessly swaps it to the custom font once it loads. - Importing 10 different font weights (100, 200, 300, etc.) when you only use 2. Every single weight is a completely separate 50kb+ HTTP download, which will absolutely slaughter your page load speed.
Interview Questions
'Inter', 'Helvetica', Arial, sans-serif)?If the primary font fails to download, or if it doesn't support a specific character (like a Japanese Kanji symbol), the browser will traverse down the fallback list one by one until it finds a font that can successfully render the character.
Real-World Example
Using the OS-native system font stack for maximum performance (The exact technique used by GitHub and Medium).
/*
Zero HTTP requests! This magic string tells the browser to use
San Francisco on Apple, Segoe UI on Windows, and Roboto on Android.
*/
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI",
Roboto, Helvetica, Arial, sans-serif;
}Check Your Knowledge
Test your understanding of Web Fonts with these quick questions.