DEV Community

Cover image for How to add a custom font to a Rails app
Marco Colli
Marco Colli

Posted on • Originally published at answers.abstractbrain.com

How to add a custom font to a Rails app

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';
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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' %>
Enter fullscreen mode Exit fullscreen mode

Originally posted on AbstractBrain Answers

Top comments (0)