Add Fonts to GatsbyJS with or without TailwindCSS
There are 2 ways how to add custom fonts to GatsbyJS project
Table of contents
Option 1: Using NPM package (preffered)
- Select a font in Fontsource
- Install the selected font using command
npm install [font-name]
- Import the font to the
gatsby-browser.js
usingimport @fontsource/[font-name]
// gatsby-browser.js
/**
* FONTS
*/
import "@fontsource/lexend-deca/300.css";
import "@fontsource/lexend-deca/500.css";
- Use the font-family property in your CSS file.
h1 {
font-family: 'Lexend Deca', 'Arial', sans-serif;
font-weight: 300;
}
TailwindCSS
If we want to use TailwindCSS there is one more step in order to make our font available across our CSS.
- Edit
tailwind.config.js
// tailwind.config.js
theme: {
fontFamily: {
'sans': ['Lexend Deca', 'Arial', 'sans-serif'],
},
}
- Call the font anywhere in the CSS
body {
font-family: theme('fontFamily.sans');
}
Option 2: Import directly to CSS
- Select a font on Google Fonts page
- Import it to the
styles.css
/* styles.css */
/**
* FONTS
*/
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
- Use the font-family property in the CSS file
h1 {
font-family: 'Roboto', 'Arial', sans-serif;
}
TailwindCSS
Using TailwindCSS with a Google Font requires to import the font AFTER the TailwindCSS styles.
- Make sure that TailwindCSS styles are loaded first
/* styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
/**
* FONTS
*/
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
- Edit the
tailwind.config.js
// tailwind.config.js
theme: {
fontFamily: {
'sans': ['Roboto', 'Arial', 'sans-serif'],
},
}
We can also use extend option.
// tailwind.config.js
extend: {
fontFamily: {
'main': ['Roboto', 'Arial', 'sans-serif'],
},
}
- Call the font anywhere in the CSS
body {
font-family: theme('fontFamily.sans');
}