How to Change Fonts

  • #Customization
Read time: 1 minute
Mitchell Christ
Mitchell Christ
Japanese Edo citizens typing on a MacBook, ukiyoe style, by Hokusai

Three simple steps to update the fonts on the Next.js + Sanity.io starter template:

  1. Grab Your Font Files.
  2. Declare your fonts in fonts.css.
  3. Assign class names the Tailwind config.

Grab Your Font Files

Whether on Google Fonts or Adobe Fonts, I recommend downloading the font file(s) directly to your codebase and serve them from local files as opposed to a CDN or CSS @import statements.

For Google Fonts

I typically will click into the CDN URLs to copy the source code only for the necessary glyph variants. For example, the CSS for Instrument Serif would be:

<style>
@import url('https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&display=swap');
</style>

Then grab the source code only for the /* latin */ variants (to reduce the payload) from fonts.googleapis.com, explained in the next step.

Make sure to download and store the fonts.gstatic.com/[...].woff2 files locally under next/public/fonts. Rename the file for easier reference.

Declare your fonts in fonts.css

Navigate to src/styles/fonts.css and paste the @font-face CSS you copied in the previous step.

๐Ÿ“ src/styles/fonts.css
/* latin */
@font-face {
	font-family: 'Instrument Serif';
	font-style: normal;
	font-weight: 400;
	font-display: swap;
	src: url(/fonts/InstrumentSerif.woff2) format('woff2');
	unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA,
		U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2191,
		U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

/* latin */
@font-face {
	font-family: 'Instrument Serif';
	font-style: italic;
	font-weight: 400;
	font-display: swap;
	src: url(/fonts/InstrumentSerif-italic.woff2) format('woff2');
	unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA,
		U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+2074, U+20AC, U+2122, U+2191,
		U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

Assign class names in tailwind.config.ts

Navigate to tailwind.config.ts and add the classes under the fontFamily object.

๐Ÿ“ tailwind.config.ts
const config: Config = {
	// ...
	theme: {
		extend: {
			// ...
			fontFamily: {
				serif: ['Instrument Serif', 'serif'],
			},
		},
	},
}

Once everything is in place, you'll be able to use your fonts with the .font-* Tailwind classes.

<div class="font-serif">
	Lorem ipsum dolor sit amet.
</div>
citizens of Edo period Japan, typing on a macbook, traditional ukiyo-e print, by Hokusai