-转载-自定义组合字体

本文转载自:众成翻译
译者:为之漫笔
链接:http://www.zcfy.cc/article/2767
原文:https://jakearchibald.com/2017/combining-fonts/

我喜欢字体Just Another Hand,我经常在我分享中的图示里用它:

(字体转图片了。——译者注)

问题在于,我不喜欢连字号和等号的字形……

(字体转图片了。——译者注)

它们的位置让人看着不舒服,位置太高了。

好在CSS支持合并字体,因而我可以创造一个类似于Just Another Hand的字体族,不同在于其中的连字符和等于号来自另一款字体: Architects Daughter

(字体转图片了。——译者注)

怎么做到

像往常一样定义@font-face

@font-face {
  font-family: 'Just Another Hand Fixed';
  font-style: normal;
  font-weight: 400;
  src: local('Just Another Hand'), local('JustAnotherHand-Regular'),
       url('https://fonts.gstatic.com/…woff2') format('woff2'),
       url('https://fonts.gstatic.com/…woff') format('woff');
}

然后再添加一个同名的@font-face,只加入连号和等于号:

@font-face {
  font-family: 'Just Another Hand Fixed';
  src: local('Architects Daughter'), local('ArchitectsDaughter'),
       url('https://fonts.gstatic.com/l/…') format('woff2'),
       url('https://fonts.gstatic.com/l/…') format('woff');
  unicode-range: U+2d, U+3d;
}

关键是unicode-range描述符。它指定上面的src只能用于连字号(U+2d)和等于号(U+3d)的码点。用以下方式可以把Unicode字符转换为码点:

'='.codePointAt(0).toString(16); // "3d"

我还使用了Google fonts’ text parameter取得“Architects Daughter”字体的子集,其中只包含连字号和等于号,把体积减至最小。woff2版只有500字节,不错!

这样就行了。然后就可以这样用:

.whatever {
  font-family: 'Just Another Hand Fixed';
}

……此时用的就是组合后的字体了!

更新:不需要用unicode-rangle吗?

Twitter和评论中有几位朋友说,不需要unicode-range,只要这样即可:

/* Subsetted font */
@font-face {
  font-family: 'Just Another Hand Fixed';
  src: url('https://fonts.gstatic.com/l/…') format('woff2') …;
}

/* Main font */
@font-face {
  font-family: 'Just Another Hand Fixed';
  src: url('https://fonts.gstatic.com/…woff2') format('woff2') …;
}

表面上可行,但性能不好。

万一浏览器先下载了子集化的字体(Subsetted font),发现这个字体缺少它需要的字形,就会下载主字体(Main font)。字体是一个一个下载。

Live demo.Network waterfall.

而使用unicode-range,浏览器预先知道自己先需要什么,因此可以并行下载字体。

Live demo.Network waterfall.

而且,如果你根本没有用到子集化字体中字形,浏览器知道自己根本不用下载它!

Live demo.Network waterfall.