CSS Web Fonts


🔹 What Are Web Fonts?

Web Fonts allow websites to use custom fonts that aren't installed on the user's system. These fonts are loaded via the internet using @font-face or font services like Google Fonts.


🔸 Why Use Web Fonts?

  • To ensure consistent typography across all devices

  • To use creative and branded fonts

  • To improve design flexibility without relying on system fonts


🔸 1. Using Google Fonts (Most Popular)

Step 1: Include the Font in <head>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
Step 2: Use in CSS
body {
  font-family: 'Roboto', sans-serif;
}

🟢 The browser will download Roboto and apply it.


🔸 2. Using @font-face (Custom Fonts)

Example:
@font-face {
  font-family: 'MyFont';
  src: url('fonts/MyFont.woff2') format('woff2'),
       url('fonts/MyFont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

p {
  font-family: 'MyFont', sans-serif;
}

🟢 Place the .woff or .woff2 files in the specified folder.


🔸 Font Formats

Format Description
.woff2 Best performance and compression
.woff Widely supported fallback
.ttf Older, larger font format
.eot Used mainly by older IE browsers
.svg Scalable font for legacy devices

🔸 Styling Web Fonts

You can style web fonts using:

font-weight: 400;     /* Normal */
font-weight: 700;     /* Bold */
font-style: italic;

🔸 Best Practices

  • Always include a fallback font.

  • Use only necessary font weights/styles.

  • Host fonts locally for better performance (if needed).

  • Preload critical fonts for fast loading.


Practice Questions

Q1. Apply Google Font Roboto to the whole body.

Q2. Import Google Font Poppins and apply it to headings.

Q3. Use @font-face to load a custom font named MyFont.

Q4. Create a class .fancy using Google Font Dancing Script.

Q5. Use font-weight: 600 for semi-bold text.

Q6. Fallback to Arial if web font fails.

Q7. Use two different fonts for headings and paragraphs.

Q8. Load a .woff2 font and apply it to a .title class.

Q9. Add italic styling to a web font.

Q10. Limit font requests to just one style and one weight.


Go Back Top