How To Use Google Fonts With TailwindCSS
There are 3 major types of generic font family:
- serif
- sans-serif
- monospace
They are used to define fallback/default font styles when user specified fonts are not available. TailwindCSS provides these 3 font family utilities by default. But you may want to add or modify them.
Integrate Google Fonts into TailwindCSS
To use Google Fonts,
- Find and import Google Font
- Add the following @import to the top of the global stylesheet, eg, global.css (Change it to be your selected font)
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@100;300;400;500;600;700&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;
- Edit tailwind.config.js file
- Add the google font like so:
theme: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
},
...
},
- Now you can apply font-sans to different elements.
Use Google Fonts in a Next.js(version 13+) + TailwindCSS project
- Import Google Fonts from next/font/google in the top level component and load the fonts. This might be pages/_app.tsx in pages router, or app/layout.tsx in app router.
import { Inter, Playfair_Display } from 'next/font/google'
const inter = Inter({
subsets: ['latin'],
display: 'swap',
variable: '--font-inter'
})
const playfair_display = Playfair_Display({
subsets: ['latin'],
display: 'swap',
variable: '--font-playfair_display'
})
- Add defined CSS variable for each font to the HTML document
in pages router:
export default function App({ Component, pageProps }: AppProps) {
return (
<main className={`${inter.variable} ${playfair_display.variable}`}>
<Component {...pageProps} />
</main>
)
}
or in app router:
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className={`${inter.variable} ${playfair_display.variable}`}>{children}</body>
</html>
)
}
- Edit tailwind.config.js file to add the CSS variables
theme: {
extend: {
fontFamily: {
sans: ['var(--font-inter)'],
serif: ['var(--font-playfair_display)']
}
},
},
- Now you can apply font-sans and font-serif to different elements