3 min read
ā¢Question 9 of 47easyHow to use fonts in Next.js?
Optimizing fonts with next/font.
What You'll Learn
- Google Fonts
- Local fonts
- Variable fonts
Google Fonts
code.txtTSX
// app/layout.tsx
import { Inter, Roboto_Mono } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
display: 'swap',
});
const robotoMono = Roboto_Mono({
subsets: ['latin'],
variable: '--font-mono',
});
export default function RootLayout({ children }) {
return (
<html lang="en" className={`${inter.className} ${robotoMono.variable}`}>
<body>{children}</body>
</html>
);
}Local Fonts
code.txtTSX
import localFont from 'next/font/local';
const myFont = localFont({
src: [
{
path: './fonts/MyFont-Regular.woff2',
weight: '400',
},
{
path: './fonts/MyFont-Bold.woff2',
weight: '700',
},
],
});
export default function Layout({ children }) {
return (
<html className={myFont.className}>
<body>{children}</body>
</html>
);
}CSS Variables
code.txtTSX
const inter = Inter({
subsets: ['latin'],
variable: '--font-inter',
});
// In CSS
// font-family: var(--font-inter);