Photo by Lautaro Andreani on Unsplash
Seamlessly Integrate Google Fonts into Your React Vite TailwindCSS Shadcn Project
If you're building a project using React, Vite, TailwindCSS, and Shadcn UI, you might want to use a custom Google font to enhance your UI. This guide will walk you through how to incorporate Google Fonts, such as "Inter", into your project.
Step-by-Step Implementation
Follow these steps to add Google Fonts to your Shadcn-powered React Vite TailwindCSS project.
1. Update the index.html
File
First, you need to include the Google Font link in your project’s HTML file. Navigate to your project’s index.html
file and insert the Google Fonts link in the <head>
section.
<!-- index.html -->
<head>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap" rel="stylesheet">
<!-- other head elements -->
</head>
This ensures that the "Inter" font is loaded from Google Fonts.
2. Customize Global Styles in globals.css
Next, update your global CSS file (commonly globals.css
or styles/globals.css
) to integrate Tailwind’s base, components, and utilities along with applying your chosen font.
/* src/styles/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
/* additional variables */
}
body {
@apply bg-background text-foreground;
font-feature-settings: "rlig" 1, "calt" 1;
}
}
/* Apply the Inter font globally */
html, body {
font-family: 'Inter', sans-serif;
font-optical-sizing: auto;
font-weight: 400;
font-style: normal;
line-height: 1.6;
font-size: 16px;
}
This applies the "Inter" font to your entire project and adjusts settings like font weight, style, and line height.
3. Configure Tailwind to Use the Inter Font in tailwind.config.js
Finally, update the Tailwind configuration file to use the Google Font in the project’s theme settings.
/** @type {import('tailwindcss').Config} */
module.exports = {
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'], // Adding Inter as the default sans-serif font
},
// Additional theme customizations
},
},
// other configurations
}
By adding 'Inter', sans-serif
to the fontFamily
property in Tailwind's theme, you ensure that the font is available for use in your Tailwind classes like font-sans
.
With these simple updates to your index.html, globals.css, and tailwind.config.js, you can seamlessly integrate Google Fonts into your React Vite TailwindCSS Shadcn project. This will ensure your project uses a custom font like "Inter" while maintaining all the benefits of TailwindCSS and Shadcn's utility-first approach.
Feel free to adjust the font size, weight, and additional features as needed for your specific project requirements.