🎉 Black Friday Sale: Over 30% off Premium Chakra UI Components
Shop NowNovember 18, 2024
There are two ways to add custom fonts to your Vite project with Chakra UI. You can either use Fontsource packages or load fonts from local files. Both methods are covered below.
Install the Google font you want to use from Fontsource. For this guide, we'll use the "Bricolage Grotesque" font as an example.
pnpm add @fontsource-variable/bricolage-grotesqueImport the font at the root of your project, referencing the css path:
main.tsx
import "@fontsource-variable/bricolage-grotesque/index.css"If you've downloaded font files from Google Fonts or have custom fonts, you can use them directly from your project. For this guide, we'll use "Bricolage Grotesque" as an example.
Place your font files in a folder like src/assets/fonts or public/fonts. For
example:
src/
assets/
fonts/
BricolageGrotesque-Regular.woff2
BricolageGrotesque-Bold.woff2
BricolageGrotesque-Variable.woff2
Create a fonts.css file (or add to your existing CSS file) with @font-face
declarations:
src/assets/fonts/fonts.css
@font-face {
font-family: "Bricolage Grotesque Variable";
src: url("./BricolageGrotesque-Variable.woff2") format("woff2");
font-weight: 100 900;
font-style: normal;
font-display: swap;
}For static font files, you can define multiple weights:
src/assets/fonts/fonts.css
@font-face {
font-family: "Bricolage Grotesque";
src: url("./BricolageGrotesque-Regular.woff2") format("woff2");
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Bricolage Grotesque";
src: url("./BricolageGrotesque-Bold.woff2") format("woff2");
font-weight: 700;
font-style: normal;
font-display: swap;
}Import the CSS file at the root of your project:
main.tsx
import "./assets/fonts/fonts.css"If you placed fonts in the public folder, reference them with absolute paths
starting with /fonts/:
@font-face {
font-family: "Bricolage Grotesque Variable";
src: url("/fonts/BricolageGrotesque-Variable.woff2") format("woff2");
font-weight: 100 900;
font-style: normal;
}Regardless of which method you used, configure the font in Chakra UI's theme
using the createSystem method:
components/ui/provider.tsx
"use client"
import { createSystem, defaultConfig } from "@chakra-ui/react"
const system = createSystem(defaultConfig, {
theme: {
tokens: {
fonts: {
heading: { value: "Bricolage Grotesque Variable" },
body: { value: "Bricolage Grotesque Variable" },
},
},
},
})heading, body, or both. Use the exact font family name as defined in your
@font-face declaration or Fontsource package.Finally, pass the system into the ChakraProvider:
components/ui/provider.tsx
export function Provider(props: ColorModeProviderProps) {
return (
<ChakraProvider value={system}>
<ColorModeProvider {...props} />
</ChakraProvider>
)
}This ensures that the custom font is applied across your entire app.