27. Web Fonts (@font-face) and Google Fonts
To ensure all users see the same custom font (not just system fonts), we use Web Fonts. The primary mechanism is the @font-face rule.
Using @font-face (Self-Hosting)
This rule allows you to define a font and link to the font files (.woff, .ttf, etc.) stored on your own server.
css @font-face { font-family: 'MyCustomFont'; /* The name you will use in font-family */ src: url('/fonts/custom-font.woff2') format('woff2'), url('/fonts/custom-font.woff') format('woff'); font-weight: normal; font-style: normal; }
/* Now use the font */ body { font-family: 'MyCustomFont', sans-serif; }
Using Hosted Services (Google Fonts)
Most developers use services like Google Fonts, which host the files for you and manage cross-browser compatibility. This is generally simpler.
How to use Google Fonts:
-
Get the Link: Select your fonts on Google Fonts and copy the generated
<link>tag. -
Paste in HTML: Place the link in your HTML
<head>: html -
Apply CSS: Use the font name exactly as provided by the service: css .article-text { font-family: 'Roboto', sans-serif; }