Using fonts in tailwind

Using fonts in tailwind

·

2 min read

Using fonts in tailwind can be tricky. You wanna add your fonts from local files and include them in your projects? Let's take a look at how this works in a Nuxt.js project!

Nuxt assets

If you're familiar with Nuxt.js you should know the directory structure. The first thing we do is to create our assets directory. Also, take a look at the [Nuxt.js documentation](https://nuxt.com/docs/getting-started/assets#assets-directory) to learn more about it.

Fonts

In our assets directory we are going to create another folder called fonts. In this directory, we have to place our fonts. This is what it could look like:

Now we can load our fonts locally and don't have to load them from an external URL.

CSS

Next we create our tailwind.css in the css directory. In our css file we apply the fonts we just added in our fonts directory. Our code should look like this:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  @font-face {
    font-family: "Montserrat-Regular";
    src: url("assets/fonts/montserrat/Montserrat-Regular.ttf") format("truetype");
    font-display: swap;
  }
  @font-face {
    font-family: "Montserrat-Bold";
    src: url("assets/fonts/montserrat/Montserrat-Bold.ttf") format("truetype");
    font-display: swap;
    font-weight: 500;
  }
}

We have defined the regular font and the font for bold. If you have more fonts you also need to apply them in your css here.

Last step would be to add the fonts to the tailwind.config.js

tailwind.config

In our tailwind.config.js we can define a theme and add our fonts to it. That's how it should look like:

const plugin = require('tailwindcss/plugin');

module.exports = {
  content: [
    './components/**/*.{vue,js}',
    './layouts/**/*.vue',
    './pages/**/*.vue',
    './plugins/**/*.{js,ts}',
    './composables/**/*.{js,ts}',
    './app.vue',
    './error.vue',
  ],
  theme: {
    fontFamily: {
      regular: ['Montserrat-Regular'],
      bold: ['Montserrat-Bold'],
    },
  },
};

Use in components

That's it! We are now ready to use our custom fonts in any of our components. The only thing we need to do is to add the class font-regular or font-bold to it. Let's take a look at how a component could look like:

<script setup>
const props = defineProps({
  sampleData: { type: Object, required: true },
});
</script>

<template>
  <div class="container mx-auto">
    <h2 class="font-bold"> {{ sampleData.headline }} </h2>
    <div class="font-regular" v-html="sampleData.text"></div>
  </div>
</template>

That's how you use google fonts which are hosted locally.

Did you find this article valuable?

Support Joschi by becoming a sponsor. Any amount is appreciated!