Tailwind CSS – Add fonts from your local
Feb 16, 2022Frequently, you may find the need to incorporate custom or non-English fonts from your local files into your Tailwind CSS project.
If you're using a Google font, the process is quite straightforward. Simply include the CSS file in your project, and make a simple adjustment to the Tailwind CSS configuration file as described below.
Google Font
The very first step is to find your font on google. Then copy the import statement and finally add in the very beginning of your input CSS file.
# input.css
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;
The next step is to edit the tailwind configuration file and add your font name on `them.fontFamily`.
module.exports = {
content: [
"./resources/**/*.blade.php",
"./resources/**/*.js",
"./resources/**/*.vue",
],
theme: {
fontFamily: {
'sans': 'Roboto'
}
},
plugins: [],
}
Custom Local Font
When you have a non-Google font stored on your local machine that you want to use in your Tailwind CSS project, you'll need to create your own font face. A font face is a CSS rule that enables you to utilize custom fonts in your web projects.
To do it, first, you need to locate the CSS file in your project (Laravel in this blog) `resources/fonts` directory.
Now it is time to create your own font faces in `resources/css/app.css` (Larvavel Project).
#resources/css/app.css
@font-face {
font-family: 'bahij';
font-weight: normal;
src: url('../fonts/BahijNazanin-Regular.woff2') format('woff2');
}
@tailwind base;
@tailwind components;
@tailwind utilities;
Note: if there are separated font files for different font weights then you can create another font face with the same `font-family` name.
#resources/css/app.css
@font-face {
font-family: 'bahij';
font-weight: normal;
src: url('../fonts/BahijNazanin-Regular.woff2') format('woff2');
}
@font-face {
font-family: 'bahij';
font-weight: bold;
src: url('../fonts/BahijNazanin-Bold.woff') format('woff');
}
@tailwind base;
@tailwind components;
@tailwind utilities;
Note: if your font type is `ttf` then the format should be `format('turetype')`.
@font-face {
font-family: 'bahij';
font-weight: bold;
src: url('../fonts/BahijNazanin-Bold.ttf') format('truetype');
}
Finally, now is the time to edit your tailwind CSS configuration file. (Add the `fontFamily`)
module.exports = {
content: [
"./resources/**/*.blade.php",
"./resources/**/*.js",
"./resources/**/*.vue",
],
theme: {
fontFamily: {
'sans': 'bahij'
}
},
plugins: [],
}
As a final tip please keep in your mind to add the directory `public/fonts` in `.gitignore` file.
Now run the command `npm run watch` for developing (Laravel project) or `npm run prod` for production.
The best