Using custom fonts
Astro supports all common strategies for adding custom typefaces to your site design. This guide will show you two different options for including web fonts in your project.
Using a local font file
Section titled Using a local font fileIf you want to add font files to your project, we recommend adding them to your public/ directory. In your CSS you can then register fonts with an @font-face statement and use the font-family property to style your site.
Example
Section titled ExampleLet’s imagine you have a DistantGalaxy.woff font file.
-
Add your font file to
public/fonts/. -
Add an
@font-facestatement to your CSS. This could be in a global.cssfile you import or in a<style>block in the layout or component where you want to use this font./* Register our custom font family and tell the browser where to find it. */ @font-face { font-family: 'DistantGalaxy'; src: url('/fonts/DistantGalaxy.woff') format('woff'); font-weight: normal; font-style: normal; font-display: swap; } -
Use the
font-familyfrom the@font-facestatement to style elements in your component or layout. In this example, the<h1>heading will have the custom font applied, while the paragraph<p>will not.src/ pages/ example.astro --- --- <h1>In a galaxy far, far away...</h1> <p>Custom fonts make my headings much cooler!</p> <style> h1 { font-family: 'DistantGalaxy', sans-serif; } </style>
Using Fontsource
Section titled Using FontsourceThe Fontsource project simplifies using Google Fonts and other open source fonts. It provides npm modules you can install for the fonts you want to use.
-
Find the font you want to use in Fontsource’s catalog. For this example, we’ll use Twinkle Star.
-
Install the package for your chosen font.
npm install @fontsource/twinkle-starpnpm install @fontsource/twinkle-staryarn add @fontsource/twinkle-star -
Import the font package in the layout or component where you want to use the font. Usually, you will want to do this in a common layout component to make sure the font is available across your site.
The import will automatically add the necessary
@font-facerules needed to set up the font.src/ layouts/ BaseLayout.astro --- import '@fontsource/twinkle-star'; --- -
Use the
font-familyas shown on that font’s Fontsource page. This will work anywhere you can write CSS in your Astro project.h1 { font-family: "Twinkle Star", cursive; }
More resources
Section titled More resourcesAdd fonts with Tailwind
Section titled Add fonts with TailwindIf you are using the Tailwind integration, you can either add an @font-face statement for a local font or use Fontsource’s import strategy to register your font. Then, follow Tailwind’s docs on adding custom font families.
Learn how web fonts work
Section titled Learn how web fonts workMDN’s web fonts guide introduces the topic.
Generate CSS for your font
Section titled Generate CSS for your fontFont Squirrel’s Webfont Generator can help prepare your font files for you.