Table of Contents
Setting up typography in Next.js using vanilla-extract & Capsize
Letters in the browser render white space above & below them. From a design perspective however, this vertical space should be reduced to the height of a capital letter. Capsize fixes this. Trimming the empty space. This note details how to set up fonts & Capsize in a Next.js project. It assumes only variable fonts are being used.
2. Remove Unrequired Boilerplate
Delete the following directories & files highlighted in red as they won't be required:
my-next-app ├── pages│ ├── api│ ├── _app.ts│ └── index.tsx├── public│ ├── favicon.ico│ └── vercel.svg├── styles ...
Replace the contents of the following files:
3. Add Font Files
For this example, we will only be using 1 font family, Inter.
Download the family & move the variable font file
Inter-VariableFont_slnt,wght.ttf into the directory
6. Create Typography Styles
Create a file
This file will hold all typographic information & define all font styles.
We are only using 1 font-family but this file is structured to allow more if required.
To get information about a font-family like the value for
wghtRange, use wakamaifondue.
The font sizes were calculated using type-scale.
Notes on why unions are used instead of enums can be found here.
7. Load Fonts
Create a file
This will act as the CSS reset & where font families will be loaded.
fontDisplay: 'optional' is being used to prevent layout shifting & a flash of invisible text on page load.
This requires preloading font files. Create a file
/pages/_document.tsx & add the following:
fontDisplay: 'optional' sets an extremely small block period & no swap period for font loading.
In my experience, even on a fast connection (25 Mbps), the font won't always load in time & the page will display the fallback.
If you require to always display the correct font & can accept a layout shift,
fontDisplay: 'swap' might be a better setting to use.
More information on font-display values can be found here.
To set the CSS reset styles in all pages within the app, import the
Lets visually test the font styles to ensure everything is working correctly.
Normally I would do this using Storybook but that is out of the scope of this note.
Create a file
/styles/test.css.ts & add the following:
This file creates a CSS class using each of our defined font sizes.
The last class,
boldText, is showing:
- ▪ how more styles can be added to font style class &
- ▪ how to use 1 of the font weights we defined earlier.
Render some text & add these styles in
The end result is typography rendering at the defined size & weight with unwanted space above & below trimmed off. The outlines around the text where produced from a browser extension: Pesticide for Chrome.