SmartCodingTips

Using Custom Fonts in CSS

Custom fonts help create a unique and branded look for your website. CSS allows you to load both local and web fonts using @font-face or services like Google Fonts.

1. Importing from Google Fonts

Visit Google Fonts, choose a font, and include the provided link in your HTML <head>:


<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
            

Then use it in your CSS:


body {
    font-family: 'Roboto', sans-serif;
}
            

2. Using @font-face

Host and load your own font files 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;
}

h1 {
    font-family: 'MyCustomFont', sans-serif;
}
            

3. Font Formats

Different browsers support different font formats. Common ones include:

  • .woff2 – modern and recommended
  • .woff – widely supported fallback
  • .ttf – TrueType, older but usable
  • .eot – for legacy Internet Explorer

4. Font Fallbacks

Always provide fallback fonts to ensure text is readable even if the custom font fails to load:


body {
    font-family: 'Open Sans', Arial, sans-serif;
}
            

5. Performance Tips

  • Use font-display: swap; to improve loading speed and avoid invisible text.
  • Only load font weights and styles you actually use.
  • Self-host fonts for full control and offline support.

Conclusion

Custom fonts enhance your design but must be handled carefully for performance and compatibility. Whether you're using web services or hosting locally, proper font integration boosts both visual appeal and user experience.