Problem: I’m trying to get a Google variable font to work (I’m okay with the non-variable ones).
I am new to the mysterious world of Google fonts, and it seems there are a lot of opinions out there on how they should be implemented.
Per suggestions around in the interwebs, if I enter this in my browser to test my <link>
tab in my <head>
:
https://fonts.googleapis.com/css2?family=Roboto+Flex:slnt,wdth,[email protected],25..150,200..700&display=swap
and I get a bunch of these:
/* latin-ext */
@font-face {
font-family: 'Roboto Flex';
font-style: oblique 0deg 10deg;
font-weight: 200 700;
font-stretch: 25% 150%;
font-display: swap;
src: url(https://fonts.gstatic.com/s/robotoflex/v26/NaNeepOXO_NexZs0b5Qrz. . ..woff2) format('woff2');
unicode-range: U+0100-02AF, U+0304, U+0308, U+0329, . . . U+1E00-1E9F;
}
I thought those were to go at the top of my .css file. But it doesn’t seem to make any difference. In fact, even if I leave it out for the non-variable fonts, as long as my <link>
tag checks out, they work fine.
The variable font does not. Here’s my .css:
font-family: "Roboto Flex", Arial;
font-weight: 400;
font-stretch: 150%;
What am I not getting?
2
Answers
Should be pretty easy if you just accept the defaults and follow Google’s instructions. I prefer the
@import
in the CSS over the<link>
in the HTML.Whenever you need to load a "custom font" you need
@font-face
rules.The syntax is based on web-standards.
In other words the CSS retrieved via google-fonts-API doesn’t have a proprietary format/syntax and is not different from a CSS you would need to load fonts locally (from your web server).
The main difference: the CSS is dynamic when loading from google’s API. Most importantly google server will apply agent detection to deliver the most suitable font files. You can easily test this by comparing the returned CSS output in Firefox vs a Chromium/blink or a Safari/Webkit browser.
Unfortunately, this approach has its flaws: for instance modern Opera versions (also Chromium/blink) are still detected as not supporting variable fonts.
Wether you add a
<link>
element in your header or a@import
rule in your CSS doesn’t really matter with regards to the returned CSS (albeit the@import
approach is considered to be less ideal in terms of loading speed and caching).Is a dynamic query loading the variable font
You could as well copy the code and paste it to your own page CSS file.
You could also download all font files and replace the
src
properties accordingly. That’s basically what you need to do as a web designer in Europe to be GDPR compliant (no cdn resources).Worth noting "Roboto Flex" provides quite a few design axes – that’s why the font-face appears more complex
Notice the properties with 2 values – specifying the possible range.
So there is no mystery =)