Skip to content

How to use custom fonts in Gatsby and Styled Components

Posted on:October 14, 2020 at 06:00 PM

Importing fonts used to be pretty straightforward. With modern JavaScript focused projects and build tools it can be quite confusing. This is the approach that worked for my Gatsby project.

I wanted to add custom fonts to my Gatsby project, but a lot of resources online seemed outdated. Some suggested directly importing font files in your TypeScript or JavaScript files but that didn’t work for me.

I use styled-components for CSS, but createGlobalStyle wouldn’t work for me since I use object syntax.

import { createGlobalStyle } from "styled-components";

createGlobalStyle({
  "@font-face": {
    // font 1
  },
  "@font-face": {
    // font 2 would override font 1
    // because the "@font-face" key is the same
  },
});

I downloaded my fonts from Google Fonts and generated the .woff and .woff2 files with the Font Squirrel Webfont Generator.

I could have used the typeface-source-sans-pro package but I didn’t want any unused font definitions, so I briefly checked how the packages in the Typefaces repository worked and copied that. It turned out to just be a CSS file. Simple enough!

@font-face {
  font-family: "Source Sans Pro";
  font-style: normal;
  font-display: swap;
  font-weight: 400;
  src: 
    local("Source Sans Pro Regular normal"), 
    local("Source Sans Pro-Regularnormal"), 
    url("./ssp-regular.woff2") format("woff2"), 
    url("./ssp-regular.woff") format("woff");
}

@font-face {
  font-family: "Source Sans Pro";
  font-style: normal;
  font-display: swap;
  font-weight: 600;
  src: 
    local("Source Sans Pro SemiBold normal"), 
    local("Source Sans Pro-SemiBoldnormal"), 
    url("./ssp-semibold.woff2") format("woff2"), 
    url("ssp-semibold.woff") format("woff");
}

I then imported it in my gatsby-browser.js. This will create a new <link> tag in your <head>.

// gatsby-browser.js
import "./src/assets/fonts/index.css";

After importing the CSS file I was able to use the fonts anywhere in my CSS like my typography.js config or my Styled Components.

const MyComponent = styled.div({
  fontFamily: `'Source Sans Pro', sans-serif`,
});

That’s it! I hope this helped you in any way.