If the fonts on the visitor’s device are not enough, you can ship your own font file and tell the browser to use it. That is what @font-face does.
@font-face {
font-family: "Juniper Sans";
src: url("fonts/juniper-sans.woff2") format("woff2");
font-weight: 400;
font-style: normal;
font-display: swap;
}
body {
font-family: "Juniper Sans", system-ui, sans-serif;
}
What each line does
font-familyis the name you choose and will use later.srcpoints to the file. Theformat()hint lets the browser skip files it cannot read.font-weightandfont-stylesay which variant this file is. To use bold, write a second@font-facefor the bold file withfont-weight: 700.font-display: swapshows text in the fallback font right away and swaps in the custom font when it has loaded. This avoids invisible text.
Use WOFF2
WOFF2 is the compressed font format supported by all modern browsers. You rarely need any other.
Keep fonts light
Every font file you add is a download. A few habits keep that small:
- Use at most two or three files (for example regular and bold).
- Include only the weights you actually use.
- Keep a fallback in your
font-familythat looks similar, so the swap is not jarring.
Licenses
Wrong path
url() in a stylesheet is relative to the CSS file. A 404 on the font file means the page quietly shows the fallback.Another route is to let a service host the files for you: Google Fonts.