Next.js Discord

Discord Forum

Any way to predetermine what a font name will be?

Answered
Lithuanian Hound posted this in #help-forum
Open in Discord
Lithuanian HoundOP
I'm trying to setup a Tailwind font family, but I'm using NextJS's mechanism of font import:
import { Open_Sans } from "next/font/google";
import localFont from "next/font/local";

When I import the font into my root layout, it of course creates a (random?) name for the font. Because of this, I can't setup the Tailwind family. Any mechanism I can use?
Answered by Giant panda
Inject the font using a CSS variable like
const fontSans = FontSans({
  subsets: ["latin"],
  variable: "--font-sans",
})

// ...
function Layout() {
  return <body className={cn(/* ... */, fontSans.variable)}>
}

then in your Tailwind config reference it like this:
fontFamily: {
  sans: ["var(--font-sans)", /* ... */],
},
View full answer

2 Replies

Giant panda
Inject the font using a CSS variable like
const fontSans = FontSans({
  subsets: ["latin"],
  variable: "--font-sans",
})

// ...
function Layout() {
  return <body className={cn(/* ... */, fontSans.variable)}>
}

then in your Tailwind config reference it like this:
fontFamily: {
  sans: ["var(--font-sans)", /* ... */],
},
Answer
Lithuanian HoundOP
Thanks! I didn't try using a variable in the tailwind config; I didn't think that would work!