DEV Community

Cover image for How to use Next.js @next/font with TailwindCSS
Leo
Leo

Posted on

How to use Next.js @next/font with TailwindCSS

I'll go straight to the point. Next.js 13 will optimize your fonts out of the box. But... how to use them alongside with TailwindCSS?

Working with the new layout.tsx

Under app/layout.tsx, import:

import { Inter, Oswald } from "@next/font/google";
Enter fullscreen mode Exit fullscreen mode

Then, initialize their instances:

const inter = Inter({ subsets: ["latin"], variable: "--font-inter" });
const oswald = Oswald({ subsets: ["latin"], variable: "--font-oswald" });
Enter fullscreen mode Exit fullscreen mode

Let's now add our font's variables as classNames inside our <html> tag:

<html lang="en" className={`${inter.variable} ${oswald.variable}`}>
Enter fullscreen mode Exit fullscreen mode

Moving to tailwind.config.js

Add both fonts to the fontFamily TailwindCSS configuration:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx}",
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {
      fontFamily: {
        inter: ["var(--font-inter)"],
        oswald: ["var(--font-oswald)"],
      },
    },
  },
  plugins: [],
};
Enter fullscreen mode Exit fullscreen mode

Finally, let's use them:

Under app/page.tsx:

export default function Home() {
  return (
    <main className="font-inter font-extralight">
      Lorem ipsum dolor, sit amet consectetur adipisicing elit.
    </main>
  );
}
Enter fullscreen mode Exit fullscreen mode

Replace font-inter with font-oswald and you'll see Oswald taking place. Isn't it beautiful? ✨

Top comments (0)