Search code examples
gatsbypostcsstailwind-css

Self-Hosted Font with Gatsby & Tailwind (PostCSS)


I was using a self-hosted font in Gatsby and that was working well. Basically I had -

  • a fonts/ folder in which all the .woff2 files were placed, with a fonts.css that had all the @font-face calls (this way because there were almost 15 @font-face calls)
  • I had configured the gatsby-source-filesystem plugin in gatsby-config.js as below
      resolve: "gatsby-source-filesystem",
      options: {
        name: "fonts",
        path: `${__dirname}/src/fonts/`
      }
    },

I've now installed Tailwind with PostCSS as below -

  • installed tailwindcss and gatsby-plugin-postcss using yarn
  • configured gatsby-config.js as below -
{
     resolve: `gatsby-plugin-postcss`,
     options: {
       postCssPlugins: [
         require(`tailwindcss`),
         require(`autoprefixer`)
       ],
     },
   },
  • imported tailwind into gatsby-browser.js as below
import "tailwindcss/base.css"
import "tailwindcss/components.css"
import "tailwindcss/utilities.css"

Tailwind is working fine but it isn't using the font I want to use.....even though I have configured it correctly (I think) in tailwind.config.js

extend: {
      fontFamily: {
        sans: ["Custom Font Family Name", ...defaultTheme.fontFamily.sans],
      },

Solution

  • Perhaps the fonts you have in ./src/fonts are not copied to public? You can check by navigate to the Network tab in the developer tools of your preferred browser, filter by font and see the response. It's likely that they're 404.

    A quick fix would be to manually copy the fonts to static directory (create one if you don't have it.)

    If you're doing something special with the fonts (for example, subfontting) you might be interested in adding hash to the fonts file & replace the file name in your font.css.