Home > other >  Custom google fonts with NextJs and tailwindCSS
Custom google fonts with NextJs and tailwindCSS

Time:12-16

I would like to use google fonts in my NextJS app. I use tailwindCSS and I already imported reference link in the _document.js Head section . In the tailwind.config file I defined my fontFamily, but when I try to use the custom class it does not apply the font family to the html element. What am I doing wrong?

My _document.js file:

import Document, { Html, Head, Main, NextScript } from "next/document";

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html>
        <Head>
          <link
            href="https://fonts.googleapis.com/css2?family=Press Start 2P&display=swap"
            rel="stylesheet"
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

tailwind.config file:

const defaultTheme = require("tailwindcss/defaultTheme");

module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {
      fontFamily: {
        press: ["Press Start 2P", ...defaultTheme.fontFamily.sans],
      },
    },
  },
  plugins: [],
};

Text where I want to use the custom font:

<h2 className="font-press text-3xl">
          This is a random text with custom google font family Press Start 2P!
</h2>

CodePudding user response:

You have to use single quotes around the font name in tailwind.config.js:

    // ...
    extend: {
      fontFamily: {
        press: ['"Press Start 2P"', ...defaultTheme.fontFamily.sans],
      },
    },

CodePudding user response:

This is my enter image description here

"next": "12.0.7","react": "17.0.2","tailwindcss": "^3.0.5"

  • Related