Web Fonts in CSS
Web Fonts in CSS — Using Custom Fonts on Your Website
Web fonts allow you to use fonts that aren’t installed on the user’s device by loading them from the web, improving typography and design flexibility.
1. Using @font-face
You can load custom fonts by defining them with @font-face:
@font-face { font-family: 'MyCustomFont'; src: url('fonts/MyCustomFont.woff2') format('woff2'), url('fonts/MyCustomFont.woff') format('woff'); font-weight: normal; font-style: normal;}Then use it:
body { font-family: 'MyCustomFont', sans-serif;}2. Using Google Fonts (Most Popular & Easy)
Add this in your HTML <head>:
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">Then in CSS:
body { font-family: 'Roboto', sans-serif;}3. Font Formats
WOFF2: Modern, compressed, best support
WOFF: Widely supported compressed format
TTF/OTF: Traditional font files, bigger size
EOT: Legacy IE format
SVG: Older iOS support
4. Font Loading Strategies
Use
font-displayto control how fonts load (optional):
@font-face { font-family: 'MyCustomFont'; src: url('fonts/MyCustomFont.woff2') format('woff2'); font-display: swap;}swapshows fallback font until the web font loads to avoid invisible text.
5. Fallback Fonts
Always provide fallback fonts to ensure readability:
font-family: 'Open Sans', Arial, sans-serif;6. Example
@import url('https://fonts.googleapis.com/css2?family=Lora&display=swap');body { font-family: 'Lora', serif; font-size: 18px; line-height: 1.6;}Would you like help setting up custom fonts for a project, or a list of popular web fonts with examples?