
I’m replacing the heading font in a project with a new variable file. Easy enough to register the new font with @font-face right?
@font-face {
font-family: "NewFont";
src: url("./fonts/NewFont-Variable.woff2") format("woff2");
font-display: swap;
font-weight: 200 700;
}
It’s declared on the headings, of course, including a fallback insurance:
/* FUTURE: :heading */
:where(h1, h2, h3, h4, h5, h6) {
font-family: "NewFont", system-ui;
}
Cool, cool. But the new font-size needs a higher value than the UA defaults, as the default sizing is too darn small:
h1 {
font-size: clamp(3.13rem, 2.74vw + 2.75rem, 5.38rem);
}
/* etc. */
Let’s say that the new font file fails to load for, you know, reasons. We get the system-ui font as a fallback:
Oh gosh, that’s huge. That doesn’t suit my UI at all.
There’s no way to set a fallback font-size for when a fallback font is used. I was really tempted to see if the experimental if() function might be a possibility as a future way to tackle it but, alas, the style(), media(), and supports() conditions it accepts can only use what the browser already knows. In other words, there’s no way to tell the browser if this font fails to load.
I ran my hand through my ever-thinning hair and remembered that we can use @font-face to register any font we want, even local ones, and give them a custom name. Say a default system font:
@font-face {
font-family: "NewFont Fallback";
src: local("system-ui");
}
Now we’ve got something to play with! There are other descriptors we can fudge with in the at-rule that adjust the font size, like size-adjust. With a little eyeball testing:
@font-face {
font-family: "NewFont Fallback";
src: local("system-ui");
size-adjust: 55%;
}
Now that can be added to the font stack:
:where(h1, h2, h3, h4, h5, h6) {
font-family: "NewFont", "NewFont Fallback", sans-serif;
}
…adding sans-serif in there in any weird case where someone’s machine doesn’t have a system-ui font. You can remove "NewFont" from the stack to see the difference:
I suppose it could work the other way and simply use size-adjust to increase the default font. Either way, conventional wisdom is typically “choose the web font that best matches your custom font.” But there are other factors to consider, I guess. Maybe you already knew all this. I hadn’t thought of that before or really run into that situation. Hopefully it’s useful for you if you hit a similar hurdle.
There are lots and lots of other @font-face descriptors you might be keen to play with if you’re more persnickety about matching than me.