Multiple Fonts
Overview
In the starter kit, I have already configured two fonts: Inter and Source Serif 4. To use those fonts, you can use the font-sans
and font-serif
class in TailwindCSS.
Customize
You can find the following piece of code in src/app/layout.tsx
and tailwind.config.ts
file:
import { Inter, Source_Serif_4 } from 'next/font/google';
// other import statements
// making an object of Inter font, and giving it variable '--font-sans'
const fontSans = Inter({ subsets: ['latin'], variable: '--font-sans' });
// making an object of Source Serif 4 font, and giving it variable '--font-serif'
const fontSerif = Source_Serif_4({
subsets: ['latin'],
style: ['italic', 'normal'],
variable: '--font-serif',
});
// some code here
<body
className={cn(
'font-sans antialiased', // making font-sans default
fontSans.variable, // with this, you can use font-sans anywhere
fontSerif.variable // with this, you can use font-serif anywhere
)}
>
// other code
// other code
fontFamily: {
sans: ['var(--font-sans)', ...fontFamily.sans],
serif: ['var(--font-serif)', ...fontFamily.serif],
},
Now using the above reference, let's try to use another font. We'll try using Space Grotesk as font-mono
.
We can very easily edit the above files as below:
import { Inter, Source_Serif_4, Space_Grotesk } from 'next/font/google';
// other import statements
// making an object of Inter font, and giving it variable '--font-sans'
const fontSans = Inter({ subsets: ['latin'], variable: '--font-sans' });
// making an object of Source Serif 4 font, and giving it variable '--font-serif'
const fontSerif = Source_Serif_4({
subsets: ['latin'],
style: ['italic', 'normal'],
variable: '--font-serif',
});
//making an object of Space Grotesk font, and giving it variable '--font-mono'
const fontMono = Space_Grotesk({
subsets: ['latin'],
variable: '--font-mono',
})
// some code here
<body
className={cn(
'font-sans antialiased', // making font-sans default
fontSans.variable, // with this, you can use font-sans anywhere
fontSerif.variable, // with this, you can use font-serif anywhere
fontMono.variable // with this, you can use font-mono anywhere
)}
>
// other code
// other code
fontFamily: {
sans: ['var(--font-sans)', ...fontFamily.sans],
serif: ['var(--font-serif)', ...fontFamily.serif],
mono: ['var(--font-mono)', ...fontFamily.mono],
},
Now as you can see, we imported Space_Grotesk
from next/font/google
and then we created an object of it.
Then we passed fontMono.variable
in the className
attribute of <body>
tag.
Other than that, we simply had to add mono: ['var(--font-mono)', ...fontFamily.mono],
in our tailwind.config.ts
and we're done!
Now you can use font-mono
as a className in any file and the font will be used.
Other resources
Custom styles: Custom styles
NextJS fonts' docs: https://nextjs.org/docs/app/api-reference/components/font
Last updated