Adding a New Font

Learn to add and use new assets in Scandi

You can add fonts in the src directory. When you reference them with url in your style sheets, they will be resolved and bundled with your application. Let's go through an example.

You can find fonts in Font squirrel, dafont.com, Everything Fonts or Google Fonts.

In our case, it is best to convert your fonts into the woff format, which is optimized for the web. See this article for more details.

Suppose you have decided to use the Staatliches and Source Sans Pro fonts. Convert them into the Woff and Woff2 formats. Then, put them in the src/style/fonts directory. Any directory under src would work, but it makes sense to store them in their own directory along with styles. Verify that your fonts are where you expect:

$ ls src/style/fonts/
sourcesanspro-regular-webfont.woff sourcesanspro-regular-webfont.woff2
staatliches-regular-webfont.woff staatliches-regular-webfont.woff2

However, they are still not imported in our styles. To actually include them into the page, create a new file, namedsrc/style/base/_font.scss, for example. First, we will need to declare the font faces:

src/style/base/_font.scss
@font-face {
font-family: 'Staatliches';
src: url(/style/fonts/staatliches-regular-webfont.woff2) format('woff2'),
url(/style/fonts/staatliches-regular-webfont.woff) format('woff');
font-weight: normal;
font-style: normal;
}
โ€‹
@font-face {
font-family: 'SourceSansPro';
src: url(/style/fonts/sourcesanspro-regular-webfont.woff2) format('woff2'),
url(/style/fonts/sourcesanspro-regular-webfont.woff) format('woff');
font-weight: normal;
font-style: normal;
}

For convenience, let's also define SCSS variables to refer to these fonts:

src/style/base/_font.scss
$font-staatliches: 'Staatliches', sans-serif;
$font-source-sans-pro: 'SourceSansPro', sans-serif;

Now, we have told the browser that these fonts exist and where to find them. However, they aren't actually being used anywhere. Let's use the Staatliches font for headings, and the Source Sans font for everything else:

src/style/base/_font.scss
body {
font-family: $font-source-sans-pro;
}
โ€‹
h1, h2, h3, h4, h5, h6 {
font-family: $font-staatliches;
}

One final change is needed - to actually include the _font.scss file as part of the styles. We can do so by importing it in src/style/main.scss (override the file if you don't already have it in your code). In the last lines of main.scss, add:

src/style/main.scss
@import './base/font';

Note: it is important that this import occurs after the import of base/_reset.scss, since, in the base theme, this is where the body font is set.

We can now refresh the page to see that the fonts have been updated:

Result: fonts updated!

Exercise: Try adding a new font and assigning it to some text! Be careful though - the more fonts you add, the less consistent the user interface looks. Besides, each additional font needs to be loaded into the browser.