Back to course

Lesson 27: Web Fonts (@font-face) and Google Fonts

CSS Mastery: From Zero to Hero in 100 Lessons

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:

  1. Get the Link: Select your fonts on Google Fonts and copy the generated <link> tag.

  2. Paste in HTML: Place the link in your HTML <head>: html

  3. Apply CSS: Use the font name exactly as provided by the service: css .article-text { font-family: 'Roboto', sans-serif; }