Astrolab
How to embed custom fonts on a static website with CSS

How to embed custom fonts on a static website with CSS

The joy of setting a handwritten-like monospaced font on your terminal and website


Published on Thu Jul 04 2024
Authored by: ravihlb

A few weeks ago I stumbled across the channel of fellow blogger Mischa van den Burg, which has some really good stuff!

He made this hour-long video called Ultimate Notetaking: My Neovim Zettelkasten Based on Obsidian - Complete Walkthrough in which his handwritten-like font really stood out to me. And I’m pretty sure he uses the Fantasque Sans Mono font on his terminal and neovim.

I thought it looked awfully comfy and really wanted to integrate that into my daily workflow. It looks so comfortable, especially for a monospace font!

So I eventually wanted to include the font on this very blog of yours and turns out I really had no idea how to do it and had to search quite a bit for it. I ended up finding a few blog posts and StackOverflow answers that really helped.

Also, I thought about putting “built with Sveltekit” on the title because this blog is built using Sveltekit + MDSVex, but these tips go for pretty much any website (or webapp!) built with html.

The Solution

  1. Download the font you want to embed into your project. Preferrably, as close as possible to your global css file.
  2. On your global css file, import your new Custom Font Regular:
@font-face {
    font-family: Custom Font Regular;
    font-display: swap;
    src: local('Custom Font Regular'), url(./fonts/CustomFont-Regular.otf);
}

body {
    font-family: Custom Font Regular;
    ...
}

Here, I’m importing the CustomFont-Regular.otf file downloaded on step 1 that was put inside a fonts/ directory.

.
├── fonts
│   └── CustomFont-Regular.otf
└── main.css

Both local() and url() are css functions used for importing resources. With url(), you can provide a local, relative path or full http remote one.

It’s smart to use local() first, since this will prompt the browser to look for an installed font first.

And that’s it! Thank you for reading this article.

References