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-face
statement to your CSS. This could be in a global.css
file you import or in a<style>
block in the layout or component where you want to use this font. -
Use the
font-family
from the@font-face
statement 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.
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.
-
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-face
rules needed to set up the font. -
Use the
font-family
as shown on that font’s Fontsource page. This will work anywhere you can write CSS in your Astro project.
Add 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.
-
Follow either of the guides above, but skip the final step of adding
font-family
to your CSS. -
Add the typeface name to
tailwind.config.cjs
.This example adds
InterVariable
andInter
to the sans-serif font stack, with default fallback fonts from Tailwind CSS.Now, all sans-serif text (the default with Tailwind) in your project will use your chosen font and the
font-sans
class will also apply the Inter font.
See Tailwind’s docs on adding custom font families for more information.
More resources
Section titled More resourcesLearn 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.