Skip to content

Instantly share code, notes, and snippets.

@barbietunnie
Last active February 25, 2025 06:51
Show Gist options
  • Save barbietunnie/33f44c11422d7e038ef965635c82b19b to your computer and use it in GitHub Desktop.
Save barbietunnie/33f44c11422d7e038ef965635c82b19b to your computer and use it in GitHub Desktop.
How to Use Custom Fonts in TailwindCSS + NextJS

How to Use Custom Fonts in TailwindCSS + NextJS

Assuming your have already set up your NextJS + Tailwind project,

1. Select your desired custom Google font

2. Scroll to the bottom and select all the styles you are interested in

Select all your desired styles

3. Copy the text within the <style> tag and paste it in your globals.css file

Import Font CSS

@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,500;1,400&display=swap');

@tailwind base;
@tailwind components;
@tailwind utilities;

4. Add a new property within the fontFamily property in tailwind.config.js under theme > extend, using the CSS rules above.

(Ensure that unquoted values are quoted, otherwise Tailwind might mistake them for a variable)

Copy Font Family

theme: {
  extend: {
    fontFamily: {
     PlayfairDisplay: ['Playfair Display', 'serif'],
    },
  },
}, 

If you will like to use the deafult Tailwind font styles as a fallback, you can include the existing theme font (Optional):

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

module.exports = {
  theme: {
    extend: {
      fontFamily: {
        PlayfairDisplay: ['Playfair Display', ...defaultTheme.fontFamily.sans]
      }
    }
  },
}

5. Use the font

You can now use reference the style using the class name font-<Defined-Font-Name>.

For example,

<h1 className="font-PlayfairDisplay text-5xl">This is using a custom font</h1>
@barbietunnie
Copy link
Author

what if i want that to be my default font in all my project? not just by typing "font-PlayfairDisplay"

You can do this by setting the class name of the font on the body tag in your root layout, after having initialised the font.

Playfair initialization

export const playfair = Playfair_Display({
  display: 'swap',
  variable: '--font-playfair',
  weight: ['400', '500', '600'],
})

Root layout definition

...
<body className={playfair.className}>
...
</body>

Alternatively, you can go simple and use the Google embed code to add the required links and class name provided in your project.

google embed code

@darrylmorley
Copy link

Nextjs provides all Google fonts, it might be better to use this. https://nextjs.org/docs/app/building-your-application/optimizing/fonts#google-fonts

@k-folab
Copy link

k-folab commented Aug 11, 2024

Thanks for this. It really helped!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment