Font face
As handy as system-ui is, sometimes you have a design file, or you simply want to use a different font.
Google fonts is a popular place to find free fonts you can use, and while they do host them, there are GDPR issues around using their hosted versions, and there is no cross-site caching that we can take advantage of anymore.
That doesn’t mean we can’t use Google fonts, we simply need to download the files and tell our CSS to use them.
To do that, once you’ve downloaded your files, you need to add the font file(s) in your project:
- index.html
Directorystyles
- style.css
Directoryassets
Directoryimages
- …
Directoryfonts
- my-awesome-font.ttf
Then, to use the font, we must use a @font-face declaration. There is more that we can do, but at a bare minimum, we must provide a name for the font using font-family, and the source of it, using src.
@font-face { font-family: "My awesome font"; src: url("../assets/fonts/my-awesome-font.ttf");}One easy way to get a performance win is to first check if the user has it installed locally, so that they don’t also have to download it.
@font-face { font-family: "My awesome font"; src: local('My awesome font'), url("../assets/fonts/my-awesome-font.ttf");}When you need multiple font weights or styles
Section titled “When you need multiple font weights or styles”With most fonts you download, you’ll have a file for every variation of that font, so one file for the normal font weight, another for bold, another for regular italic, another for bold italic, and so on.
You should only include the files that you’ll actually be using (fonts tend to be heavy, and can cause performance issues if you use too many variants). Then, we can declare them in the same way, telling the browser it’s a variant by including the weight or style in our declaration.
@font-face { font-family: "My awesome font"; src: url("../assets/fonts/my-awesome-font.ttf");}
@font-face { font-family: "My awesome font"; src: locale('My awesome font'), url("../assets/fonts/my-awesome-font-BOLD.ttf"); font-weight: bold;}
@font-face { font-family: "My awesome font"; src: locale('My awesome font'), url("../assets/fonts/my-awesome-font-ITALIC.ttf"); font-style: italic;}The name we provide for the font-family is whatever we want it to be. I could call it xyz if I wanted to. Whatever we put there is what we reference when using the font in our declarations later on. By having the same name in all three declarations above, the browser knows the other two are the italic and bold variants of that font.