How to add fonts to a Gatsby app
In this tutorial, we are going to learn about how to add the custom fonts to a gatsby app.
Adding local fonts
-
Open the gatsby project in your favorite code editor.
-
Create a new folder called
fonts
inside thesrc
folder. -
Download the fonts locally and place them inside the
fonts
folder. -
Open your
layout.css
file and load the font by referencing its path like this.
@font-face {
font-family: 'Oxygen';
src: local('Oxygen'), url(../fonts/Oxygen/Oxygen-Regular.ttf) format('truetype');
}
Here I added an Oxygen
font.
Now, we can use this font in the css classes like this.
.title{
font-family: Oxygen, serif;
color: #0004;
}
Adding google fonts
If you like to use google fonts (API) instead of local fonts, you need to install a new plugin called
gatsby-plugin-google-fonts
that adds the font stylesheet to a <head>
tag of every page in your gatsby app.
Run the following command to install the plugin.
npm i gatsby-plugin-google-fonts
Now, add the following configuration to the gatsby-config.js
file by replacing it with your font name.
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-google-fonts`,
options: {
fonts: [
`Oxygen` ],
display: 'swap'
}
}
]
}
you can also specify font weights like this.
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-google-fonts`,
options: {
fonts: [ `Oxygen\:300,400,700`,
],
display: 'swap'
}
}
]
}
you can also add the multiple fonts like this.
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-google-fonts`,
options: {
fonts: [
`Oxygen\:300,400,700`,
`Red Rose`, // second font ],
display: 'swap'
}
}
]
}