I recently set up custom fonts in a project using Next.js and Tailwind CSS. Here’s how you can do it:
Adding Font Files
Add the font files to the public folder. For example, if you are using the Inter font family, you can create public/fonts/
and add the font files directly there.
Setting Up Font Faces
Update your global CSS file to add the new font-face declarations:
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Add the font using @font-face */
@font-face {
font-family: "Inter";
src: url(/fonts/Inter-Regular.woff2) format("woff2");
font-weight: 400;
font-style: normal;
font-display: swap;
}
Configuring Tailwind
Update the Tailwind configuration file (tailwind.config.js
) to generate a class for the new font:
module.exports = {
content: [
// your content paths
],
theme: {
extend: {
fontFamily: {
inter: ["Inter", "sans-serif"],
},
},
},
plugins: [],
}
Using the Custom Font
Use the generated class name to apply the custom font. In this case, you can use the generated font-inter
class in your components:
<h1 className="font-inter text-2xl font-bold">
This text uses the Inter font
</h1>