iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Web Fonts

A web font is a typeface loaded from the network instead of relying on what's installed on the user's device. Two main ways: a service like Google Fonts, or self-hosting with @font-face.

Option 1: Google Fonts

HTML + CSS
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">

body { font-family: "Inter", system-ui, sans-serif; }

Option 2: Self-hosted with @font-face

CSS
@font-face {
  font-family: "Inter";
  src: url('/fonts/Inter.woff2') format('woff2');
  font-weight: 100 900;     /* range — for variable fonts */
  font-display: swap;       /* show fallback first, swap when loaded */
}

font-display values

ValueBehaviour
swapUse fallback immediately; swap when the web font loads. Best UX.
fallbackShort invisible period, fallback after 100ms, swap if loaded within 3s.
optionalUse if it's already cached; otherwise stick with fallback.
blockBrief invisible period, then wait — text is invisible while loading.
Tip: Self-host fonts for performance and privacy when you can. Add font-display: swap and you'll never see a flash of invisible text.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Web Fonts</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Choose the font-display value that swaps the web font in once it loads.

@font-face { font-family: 'Inter'; src: url('Inter.woff2'); font-display: ; }

Test yourself

Q1. Which at-rule declares a custom web font?
Q2. Which `font-display` value gives the best loading UX?
Q3. Which format do modern web fonts ship in for performance?

Discussion

Loading…