sherry
Multiple fonts in Next.js
In a Next.js app with Tailwind CSS, there are several ways to use multiple fonts. Here are the main approaches: 1. **Using Next.js Built-in Font Optimization (Recommended)** ```javascript // 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> ) } ``` 2. **Configure Tailwind CSS** ```javascript // tailwind.config.js module.exports = { theme: { extend: { fontFamily: { inter: ['var(--font-inter)'], roboto: ['var(--font-roboto)'], poppins: ['var(--font-poppins)'], }, }, }, } ``` 3. **Use in your components** ```jsx // 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> ) } ``` 4. **Alternative: Using CSS Variables** ```javascript // styles/globals.css @layer base { :root { --font-inter: 'Inter', sans-serif; --font-roboto: 'Roboto', sans-serif; --font-poppins: 'Poppins', sans-serif; } } ``` 5. **Using Local Fonts** ```javascript // 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> ) } ``` 6. **Using Multiple Weights/Styles** ```javascript import { Roboto } from 'next/font/google' const roboto = Roboto({ weight: ['100', '300', '400', '500', '700', '900'], style: ['normal', 'italic'], subsets: ['latin'], variable: '--font-roboto', }) ``` 7. **Using with CSS Modules** ```css /* styles/Home.module.css */ .title { font-family: var(--font-inter); } .description { font-family: var(--font-roboto); } ``` 8. **Using with Styled Components** ```javascript 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.