Introduction#
GitHub this note shows how to setup font in nextjst with next/font and tailwind
- Use next/font and className
- Use css variable with tailwind css
- Use global.css
Setup Project#
Let create a new nextjs project
npx create-next-app@latest .
Install next/font which help install font into web server without fetching the gogole font each time users request a page
npm i next/font
Project structure
|--app|--global.css|--page.tsx|--layout.tsx|--next.config.js|--tailwind.config.ts|--tsconfig.json
Next Font#
- Option 1. font.className
- Option 2. css variable
Option 1. let use next font in the laytout.tsx by using font.className
import "./globals.css";import type { Metadata } from "next";import { Space_Grotesk, Inter } from "next/font/google";const space = Space_Grotesk({subsets: ["latin"],variable: "--font-space-grotestk",});const inter = Inter({subsets: ["latin"],variable: "--font-inter",});export const metadata: Metadata = {title: "Create Next App",description: "Generated by create next app",};export default function RootLayout({children,}: {children: React.ReactNode;}) {return (<html lang="en"><body className={space.className} font-sans`}>{children}</body></html>);}
Option 2. we also can setup and use css varialbe with tailwind css
- Define the varialbe using next font in layout.tsx
- Define the css variable in the tailwind.config.ts
import type { Config } from "tailwindcss";const config: Config = {content: ["./pages/**/*.{js,ts,jsx,tsx,mdx}","./components/**/*.{js,ts,jsx,tsx,mdx}","./app/**/*.{js,ts,jsx,tsx,mdx}",],theme: {extend: {fontFamily: {sans: ["var(--font-space-grotestk)"],},backgroundImage: {"gradient-radial": "radial-gradient(var(--tw-gradient-stops))","gradient-conic":"conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",},},},plugins: [],};export default config;
Then we can use it in layout.tsx
export default function RootLayout({children,}: {children: React.ReactNode;}) {return (<html lang="en"><body className={`${space.variable} font-sans`}>{children}</body></html>);}
Global CSS#
Here is an example of global.css to define style for header h1
@tailwind base;@tailwind components;@tailwind utilities;h1 {font-size: x-large;font-weight: bold;color: blue;}