In a Next.js app with Tailwind CSS, there are several ways to use multiple fonts. Here are the main approaches:
- Using Next.js Built-in Font Optimization (Recommended)
// app/layout.js or pages/_app.js
import { Inter, Roboto, Poppins } from 'next/font/google'
const inter = Inter({
subsets: ['latin'],
variable: '--font-inter',
})
const roboto = Roboto({
weight: ['400', '700'],
subsets: ['latin'],
variable: '--font-roboto',
})
const poppins = Poppins({
weight: ['400', '600'],
subsets: ['latin'],
variable: '--font-poppins',
})
export default function RootLayout({ children }) {
return (
<html lang="en" className={`${inter.variable} ${roboto.variable} ${poppins.variable}`}>
<body>{children}</body>
</html>
)
}
- Configure Tailwind CSS
// tailwind.config.js module.exports = { theme: { extend: { fontFamily: { inter: ['var(--font-inter)'], roboto: ['var(--font-roboto)'], poppins: ['var(--font-poppins)'], }, }, }, }
- Use in your components
// Using in components
function MyComponent() {
return (
<div>
<h1 className="font-inter">This uses Inter font</h1>
<p className="font-roboto">This uses Roboto font</p>
<span className="font-poppins">This uses Poppins font</span>
</div>
)
}
- Alternative: Using CSS Variables
// styles/globals.css @layer base { :root { --font-inter: 'Inter', sans-serif; --font-roboto: 'Roboto', sans-serif; --font-poppins: 'Poppins', sans-serif; } }
- Using Local Fonts
// app/layout.js or pages/_app.js
import localFont from 'next/font/local'
const myLocalFont = localFont({
src: '../fonts/my-local-font.woff2',
variable: '--font-local',
})
export default function RootLayout({ children }) {
return (
<html lang="en" className={myLocalFont.variable}>
<body>{children}</body>
</html>
)
}
- Using Multiple Weights/Styles
import { Roboto } from 'next/font/google' const roboto = Roboto({ weight: ['100', '300', '400', '500', '700', '900'], style: ['normal', 'italic'], subsets: ['latin'], variable: '--font-roboto', })
- Using with CSS Modules
/* styles/Home.module.css */ .title { font-family: var(--font-inter); } .description { font-family: var(--font-roboto); }
- Using with Styled Components
import styled from 'styled-components' const Title = styled.h1` font-family: var(--font-inter); ` const Description = styled.p` font-family: var(--font-roboto); `
Remember:
- Next.js font optimization automatically handles performance optimizations like preloading and self-hosting
- The
variable
option creates a CSS variable that you can reference in your Tailwind config - You can combine multiple font families in a single className
- Always include fallback fonts for better performance and reliability
This setup gives you flexibility to use different fonts throughout your application while maintaining good performance and optimization.