How to Use Google Fonts in CSS: Simple Steps
To use
Google Fonts in CSS, first include the font link in your HTML <head> using a <link> tag from Google Fonts. Then, apply the font in your CSS using the font-family property with the font name in quotes.Syntax
Using Google Fonts involves two main parts:
- Include the font link: Add a
<link>tag in your HTML<head>to load the font. - Apply the font in CSS: Use the
font-familyproperty with the font name exactly as provided by Google Fonts.
html/css
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet"> body { font-family: 'Roboto', sans-serif; }
Example
This example shows how to load the 'Roboto' font from Google Fonts and apply it to the whole page's text.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Google Fonts Example</title> <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet"> <style> body { font-family: 'Roboto', sans-serif; font-size: 1.2rem; margin: 2rem; color: #333; } </style> </head> <body> <h1>Welcome to Google Fonts</h1> <p>This text uses the Roboto font loaded from Google Fonts.</p> </body> </html>
Output
A webpage with a heading and paragraph text displayed in the Roboto font, which is clean and modern.
Common Pitfalls
- Forgetting to include the
<link>tag in the HTML<head>will cause the font not to load. - Not using quotes around font names with spaces (e.g., 'Open Sans') in CSS can cause errors.
- Not providing a fallback font (like
sans-serif) can cause inconsistent appearance if the font fails to load.
css
/* Wrong: Missing quotes for font with spaces */ p { font-family: 'Open Sans', sans-serif; } /* Right: Quotes around font name */ p { font-family: 'Open Sans', sans-serif; }
Quick Reference
Remember these quick tips when using Google Fonts:
- Always copy the exact
<link>tag from Google Fonts. - Use quotes around font names with spaces in CSS.
- Include a generic fallback font like
seriforsans-serif. - Use
font-display=swapin the URL for better loading performance.
Key Takeaways
Include the Google Fonts
<link> tag in your HTML <head> to load fonts.Use the exact font name in CSS with quotes if it contains spaces.
Always add a fallback font family for consistent display.
Use
font-display=swap in the Google Fonts URL for better user experience.Test your page to ensure the font loads and displays correctly.