#Adding a custom font with Tailwind v4

4 messages · Page 1 of 1 (latest)

sharp rock
#

How do I use a custom font with my Astro site when I'm using TailwindCSS v4?

upbeat brookBOT
#

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

#

To use a custom font with your Astro site when using TailwindCSS v4, follow these steps:

  1. Add your custom font file
    Place your font file (e.g., MyFont.woff2) in a directory such as src/assets/fonts/ (recommended to avoid duplication in the build output) see note.

  2. Register the font with @font-face
    In your global CSS file (e.g., src/styles/global.css), add an @font-face declaration:

    @font-face {
      font-family: 'MyFont';
      src: url('../assets/fonts/MyFont.woff2') format('woff2');
      font-weight: normal;
      font-style: normal;
      font-display: swap;
    }
    
  3. Configure Tailwind to use your custom font
    In your tailwind.config.mjs, extend the fontFamily property to include your custom font:

    /** @type {import("tailwindcss").Config} */
    export default {
      content: ["./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}"],
      theme: {
        extend: {
          fontFamily: {
            sans: ["'MyFont'", "sans-serif"],
          },
        },
      },
      plugins: [],
    };
    

    Alternatively, you can set a CSS custom property in your global CSS and reference it in Tailwind:

    @import 'tailwindcss';
    @theme {
      --font-sans: 'MyFont', 'sans-serif';
    }
    

    And in your Tailwind config:

    fontFamily: {
      sans: ["var(--font-sans)"],
    }
    

    Register fonts in Tailwind

  4. Import your global CSS
    Make sure your global CSS file is imported in your main layout or entry point so the font and Tailwind styles are applied:

    ---
    

// In your layout or root component
import "../styles/global.css";