To use the Experimental Fonts API in Astro and apply the imported font via a CSS file, you need to:
- Configure the font in astro.config.mjs using the Experimental Fonts API.
- Use the generated CSS variable in your CSS file for the font-family.
Here’s how you can do it:
1. Configure the font in astro.config.mjs
For example, to use "Noto Sans" from Google Fonts:
import { defineConfig, fontProviders } from "astro/config";
export default defineConfig({
experimental: {
fonts: [
{
provider: fontProviders.google(),
name: "Noto Sans",
cssVariable: "--font-noto-sans"
}
]
}
});
This will make the font available as a CSS variable (--font-noto-sans) in your project Experimental fonts API usage.
2. Use the CSS variable in your CSS file
You should reference the CSS variable in your CSS, not the font name directly. For your use case, update your CSS like this:
.noto-sans-enabled {
font-family: var(--font-noto-sans), 'Noto Sans JP', 'Noto Sans Thai Looped', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
This ensures that the "Noto Sans" font loaded via the Experimental Fonts API is used first, and the rest are fallbacks.
3. Add the <Font /> component to your <head>
In your layout or head component, import and use the <Font /> component to inject the font and preload it:
---import { Font } from 'astro:assets';---
<Font cssVariable="--font-noto-sans" preload />
Summary