How to use google font for Blazor on Index.razor page

Viewed 3170
@page "/"

<style>
@import url('https://fonts.googleapis.com/css2?family=Work+Sans');
    body {
        margin: 0;
        font-family: 'Work Sans';
        color: #4d4d4d;
    }
        
</style>

In React.js I can simply use the @import to use tag to use Google Font, but in Blazor I got the error The name 'import' does not exist in current context. What is the correct way of using Google Font globally for a Blazor app.

2 Answers

@ is used to prefix Razor code, so you need to escape it with a second @. Try:

 . . .
<style>
@@import url('https://fonts.googleapis.com/css2?family=Work+Sans');
 . . .

Alternatively, if you want this localized to a single page, use CSS-Isolation:

  • Create an Index.razor.css file in the same directory as Index.razor.
  • This is a "normal" css file, so you can write css as you would normally without worrying about escaping @.

In blazor, adding font's is a little bit more complex than reactjs.

Steps

  1. Add a new directory called fonts to wwwroot
  2. Download .woff font file
  3. Copy .woff file to the fonts directory in wwwroot
  4. Then in site.css apply the following CSS
@font-face {
    font-family: '<FONT-FAMILY>';
    src: url('../fonts/<FONT.WOFF>');
}

replace FONT.WOFF with the name of your font and FONT-FAMILY with the name of the font family you're using! I got this from this blog

Related