Heim > Fragen und Antworten > Hauptteil
P粉5671123912023-08-27 10:45:57
Google字体的用户界面目前仍然更喜欢静态/单重的CSS输出。
但是您可以手动强制API输出可变字体的@font-face
规则:
https://fonts.googleapis.com/css2?family=Inconsolata:wdth,wght@50..200,200..900
重要的是使用'..'作为范围分隔符 - 否则您将得到一个包含多个静态woff2
文件URL的CSS。
此外,Google的API使用一些用户代理检测(也称为浏览器嗅探)来提供向后兼容性(对于不支持可变字体的浏览器)。 这是很有道理的...不幸的是,这并不是很好用:一些像Opera(完美支持VF)这样的浏览器也会接收到静态字体。 (这可能也适用于其他基于Chromium/Blink的浏览器)
作为解决方法,我建议在Firefox中打开上面的CSS URL。结果应该类似于:
@font-face { font-family: 'Inconsolata'; font-style: normal; font-weight: 200 900; font-stretch: 50% 200%; src: url(https://fonts.gstatic.com/s/inconsolata/v31/QldKNThLqRwH-OJ1UHjlKGlZ5qg.woff2) format('woff2'); }
注意font-weight
和font-stretch
属性值包含2个值,表示权重/宽度的范围。这是一个很好的指示器,您已经获取了正确(可变)的规则。
@font-face {
font-family: "Inconsolata";
font-style: normal;
font-weight: 200 900;
font-stretch: 50% 200%;
src: url(https://fonts.gstatic.com/s/inconsolata/v31/QldKNThLqRwH-OJ1UHjlKGlZ5qg.woff2) format("woff2");
}
body {
font-size: 36px;
font-family: sans-serif;
}
h2 {
font-size: 0.5em;
color: red;
}
p {
font-family: Inconsolata;
transition: 0.8s;
}
.customMap {
font-family: sans-serif;
}
@font-face {
font-family: "Inconsolata2";
src: url(https://fonts.gstatic.com/s/robotocondensed/v25/ieVl2ZhZI2eCN5jzbjEETS9weq8-19K7DQ.woff2) format("woff2");
font-stretch: 50%;
}
@font-face {
font-family: "Inconsolata2";
src: url(https://fonts.gstatic.com/s/roboto/v30/KFOjCnqEu92Fr1Mu51TLBCc6CsQ.woff2) format('woff2');
font-stretch: 200%;
font-style: normal;
font-weight: normal;
}
.customMap {
font-family: "Inconsolata2";
font-style: normal;
}
<p style="font-family:sans-serif; font-size:12px">Font-stretch: <input type="range" id="fontStretch" value="50" min="50" max="200" step="5"></p>
<p style="font-family:sans-serif; font-size:12px">Font-weight: <input type="range" id="fontWeight" value="200" min="200" max="900" step="10"></p>
<p id="variableTest" style="font-stretch:50%" class="inconsolata variableTest">Hamburgefons</p>
<h2>Variable fonts Example</h2>
<p>
<span style="font-stretch: ultra-condensed">P</span>
<span style="font-stretch: extra-condensed">P</span>
<span style="font-stretch: condensed">P</span>
<span style="font-stretch: semi-condensed">P</span>
<span style="font-stretch: normal">P</span>
<span style="font-stretch: semi-expanded">P</span>
<span style="font-stretch: expanded">P</span>
<span style="font-stretch: extra-expanded">P</span>
<span style="font-stretch: ultra-expanded">P</span>
</p>
<h2>Static fonts Example (custom fonts to widths mapping)</h2>
<p class="customMap">
<span style="font-stretch: 50%">g</span>
<span style="font-stretch: 200%">g</span>
</p>
<script>
fontStretch.addEventListener('change', (e) => {
variableTest.style.fontStretch = e.currentTarget.value + '%';
});
fontWeight.addEventListener('change', (e) => {
variableTest.style.fontWeight = e.currentTarget.value;
})
</script>