在 @font-face 中声明字体属性有什么讲究?

Avatar of Geoff Graham
Geoff Graham

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200 美元的免费额度!

我希望你用你最好的 Seinfeld 的语气大声读出这个标题。

我们论坛中一个 最近的问题 使我意识到,除了通常的 font-familysrc 之外,还可以向 @font-face 添加更多属性。这些属性有什么用?为什么要在那里声明其他字体声明?

我习惯于这样写 @font-face

@font-face {
  font-family: "My Custom Font";
  src: url("path/to-font-file.woff2");
}

但是 规范 确实包含更多描述符

@font-face {
  font-family: <family-name>;
  src: <url>;
  unicode-range: <urange>;
  font-variant: normal | [ <east-asian-variant-values> || <east-asian-width-values> || ruby ];
  font-feature-settings: normal | <feature-tag-value>;
  font-stretch: normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded;
  font-weight: normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
  font-style: normal | italic | oblique;
}

在查看字体服务生成的 @font-face 代码时,你会经常看到这一点。

它们是守门员!

这是一个你可以用来思考 @font-face 声明块的类比。如果字体通过了守门员,它将被下载并使用。

font-family 是显而易见的。您正在声明一个新的字体系列以供使用,因此任何想要使用此字体的元素都需要具有匹配的字体系列。

@font-face {

  /* Gatekeeper: font-family on another element must match this to be used. */
  font-family: 'Open Sans';

  src: url(my-font.woff2) format('woff2');

}

body {
  /* Match! */
  font-family: 'Open Sans';
}

h1, h2 {
  /* No match */
  font-family: 'Different Font';
}

它们(大多)都是守门员

除了 font-variantfont-feature-settings 之外,所有属性都可以用作过滤器,在值匹配时指示浏览器下载和使用字体文件。

@font-face {

  /* Only download and use if element matches this font-family */
  font-family: 'My Font';

  /* Only download and use if element matches this font-style */
  font-style: italic;

  /* Only download and use if element matches this font-weight */
  font-weight: 700;

  src: url(my-bold-and-italic-font.woff2) format('woff2');

  /* Only download and use if these characters are used */
  unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
}

也许图表解释会更有帮助

一个显示 HTML、与该 HTML 匹配的 CSS 选择器以及最终应用的 @font-face 声明块的图表。

更多阅读