- Read Tutorial
- Watch Guide Video
In the last video, we talked about using built-in fonts for your pages. What happens if you don't like any of the built-in fonts, and want to create a new one?
To do this, go to any font website like dafont.com and pick a font you like. For this application, I want to use a cool font called "Hunger Games" and I downloaded it to my system. Next, I'm going to create a new folder called fonts
inside my assets
folder and drag the hungergames.ttf
file here.
Now, go back to your code and click on the fonts folder to check if your new font file is in it. Then, go to the file application.rb
located inside your config directory. At the bottom, add a couple lines of code.
config.assets.enabled = true config.assets.path << Rails.root.join('/app/assets/fonts')
In this code, we are first turning on the assets, and then we are adding to the paths array, as it's a new path that was not built-in. Earlier, we added the fonts directory, but the file system does not know about it. So, we are taking the root of the application and appending a path to it. As a result, when the application starts up, it will add the new folder to the assets path. If we don't have this line, then the application will bypass our fonts folder.
Once this path is set, go back to the file styles.scss
and right at the top, call the font-family so we can have access to it through the rest of the file.
@font-face { font-family: "Hunger Games"; src: url ('/assets/Hunger_Games'); }
In this code, we are setting the font-family and linking the source URL. If you notice, we no longer have to mention the fonts
folder in the path because the application now knows about it and will automatically compile the fonts file in assets folder.
Now, to call this font in the header tag, change the font-family inside it.
h1{ font-family: "Hunger Games", "Arial Black", sans-serif; }
This is what the updated styles.scss
should look like.
Restart the server for the changes to take effect. A rule of thumb is to restart the server every time you make changes to any directory except the app
directory. If you go to the browser now, you can see that the font has updated.
You can make other changes too. Like for example, you want to change the font -size, you can say
h1{ font-family: "Hunger Games", "Arial Black", sans-serif; font-size: 3.5em; }
This will update your home page.
So, that's how you integrate custom fonts into a rails application.