#I am using the experimental fonts api with local fonts. How do I specify the weight in a component?

4 messages · Page 1 of 1 (latest)

green cedar
#

I want the header to have a different weight than say a p tag. How do I do this? I am using tailwindv3 with Astro if it matters

amber thistleBOT
#

Hi @green cedar. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

When using Astro’s experimental fonts API with local fonts, you specify the available font weights in your astro.config.mjs under the variants array for your font. For example:

import { defineConfig } from "astro/config";
export default defineConfig({
  experimental: {
    fonts: [{
      provider: "local",
      name: "Custom",
      cssVariable: "--font-custom",
      variants: [
        {
          weight: 400,
          style: "normal",
          src: ["./src/assets/fonts/custom-400.woff2"]
        },
        {
          weight: 700,
          style: "normal",
          src: ["./src/assets/fonts/custom-700.woff2"]
        }
      ]
    }]
  }
});

This makes both 400 (normal) and 700 (bold) weights available for your font Local font variants.

To use these weights in your components, you reference the CSS variable for your font (e.g., var(--font-custom)) in your CSS or Tailwind config. Then, you can use the font-weight property (or Tailwind’s font-normal, font-bold, etc.) to select the desired weight for each element.

For example, in your component:

---
import { Font } from 'astro:assets';
---
<Font cssVariable="--font-custom" preload />
<h1 class="font-custom font-bold">Header with bold weight</h1>
<p class="font-custom font-normal">Paragraph with normal weight</p>
<style is:global>
  .font-custom {
    font-family: var(--font-custom);
  }
</style>

In your Tailwind config, register the custom font:

// tailwind.config.mjs
export default {
  theme: {
    extend: {
      fontFamily: {
        custom: ["var(--font-custom)"]
      }
    }
  }
};
#

Now, using Tailwind’s font-bold or font-normal classes on elements will apply the corresponding weight, as long as you have defined those weights in your font variants Usage Local font variants.

Summary:

  • Define each weight you want to use in the variants array in astro.config.mjs.
  • Reference the font via its CSS variable in your Tailwind config.
  • Use Tailwind’s font weight utilities (font-bold, font-normal, etc.) in your components to select the weight.

Let me know if you need a more detailed example!

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: