AbstractBrain Answers About us

How to add a custom font to a Rails app

Question

I would like to download an open source font from GitHub and use it for a Ruby on Rails application.

I don’t want to use a CDN or Google Fonts: I would like to include the font directly in the application, for better security and privacy.

Where should I add the font in the Rails application? How can I use this font in the CSS?

Answer

First you need to create the folder app/assets/fonts if it doesn’t exist yet: this is the default directory for font assets in Rails.

Then download the font file from GitHub. For example Inter is a great choice and it is already used by many sites and by Tailwind UI. Move the file (e.g. Inter-roman.var.woff2) in the fonts directory.

Now you can use the font like a normal asset of the asset pipeline: for example you can use the helpers like asset_path and font_url to refer to it.

In order to use the font in the CSS you need a font face declaration:

@font-face {
  font-family: 'Inter var';
  font-style: normal;
  font-weight: 100 900;
  font-display: swap;
  src: font-url('Inter-roman.var.woff2') format('woff2');
  font-named-instance: 'Regular';
}

Note the use of the font-url helper, which is available in SASS files.

Finally you can use your font:

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

You can also speed up the loading of the font and avoid the page glitch while the font is loading using <link rel="preload">. Add this code to the <head> section of the application layout:

<%= preload_link_tag 'Inter-roman.var.woff2' %>