Onjsdev

Share


How to Use Next Google Fonts With TailwindCSS


By onjsdev

Dec 14th, 2023

In this article, we will cover how to use google next/font with Tailwind CSS in a next 13 application Step 1: Importing the Fonts

Let's start by importing our desired fonts like Inter and Roboto Mono from Google Fonts using the next/font/google module. Choose any font you want

import { Inter, Roboto_Mono } from 'next/font/google';

Step 2: Defining CSS Variables

To integrate these fonts with Tailwind CSS, we'll utilize CSS variables. Set the variable option in the font configuration for both Inter and Roboto Mono:

const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-inter',
});

const roboto_mono = Roboto_Mono({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-roboto-mono',
});

These options ensure smooth font loading and define CSS variables named --font-inter and --font-roboto-mono respectively.

Step 3: Adding Variables to the HTML

Next, we need to inject these variables into our HTML document. Access the variable property of each font object and add it as a className to the html element:

export default function RootLayout({ children }) {
  return (
    <html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}>
      <body>{children}</body>
    </html>
  );
}

Now, our HTML is aware of the custom font variables.

Step 4: Updating Tailwind Configuration

The final step involves integrating these variables with Tailwind CSS. Open your tailwind.config.js file and navigate to the fontFamily section within the theme object. Extend the default font families by referencing the CSS variables:

module.exports = {
  theme: {
    extend: {
      fontFamily: {
        sans: ['var(--font-inter)'],
        mono: ['var(--font-roboto-mono)'],
      },
    },
  },
};

This associates the sans and mono families in Tailwind with your custom fonts.

Step 5: Applying Fonts with Tailwind Utility Classes

That's it! You can now utilize Tailwind's utility classes like font-sans and font-mono to effortlessly apply your custom fonts to specific elements throughout your Next.js project.

Conclusion

I hope this article provides a clear and concise guide to achieving beautiful and customized font integration in your Next.js projects.

Thank you for reading.