学透CSS-text-rendering,一个掘金都在用的CSS属性。

3,112 阅读3分钟

大家好,我是半夏👴,一个刚刚开始写文的沙雕程序员.如果喜欢我的文章,可以关注➕ 点赞 👍 加我微信:frontendpicker,一起学习交流前端,成为更优秀的工程师~关注公众号:搞前端的半夏,了解更多前端知识! 点我探索新世界!

前言

某次浏览沸点的时候,无意间的打开控制台,偶遇了text-rendering。

这个没有用过的新鲜属性,让我瞬间开心了起来,又可以水一篇文章了学会新的属性了。

兼容性

掘金都在用,我觉得行!

text-rendering

MDN

定义浏览器渲染引擎如何渲染字体。浏览器会在速度、清晰度、几何精度之间进行权衡。

该属性是 SVG 的属性而不是标准的 CSS 属性。但是 Gecko(Firefox) 和 Webkit(Chrome、Safari) 内核的浏览器允许该属性在 Windows、Mac OS 和 Linux 操作系统中应用于 HTML 和 XML 内容。

属性值

optimizeSpeed 优先考虑渲染速度,禁用字距和连写

optimizeLegibility 优先考虑易读性,启用字距和连写.

MDN

一个视觉上很明显的效果是,optimizeLegibility 属性值会在某些字体(比如,微软的 Calibri,Candara,Constantia 和 Corbel 或者 DejaVu 系列字体)小于20px 时把有些相邻字符连接起来

geometricPrecision 优先考虑几何精度。

例子-连写

设置字体尺寸是16px

 p {
  font: 16px "Constantia", "Times New Roman", "Georgia", "Palatino", serif;
}

<p class="auto">finder auto</p>
<p class="speed">finder speed</p>
<p class="legibility">finder legibility</p>
<p class="geometricPrecision">finder geometricPrecision一致,启用了连体。</p>

谷歌下的效果

谷歌浏览器: optimizeSpeed禁用了连写,导致finder无法使用连写字体。

optimizeLegibility启用了连写,finder中的f和i启用了连写字体。

火狐下的效果

火狐浏览器全部启用了连写。

optimizeLegibility-20px阈值

上面optimizeLegibility我们引用了MDN的一段话:小于20px 时把有些相邻字符连接起来。

在chrome下实测,20px阈值仿佛不存在。

在火狐浏览器下实测,20px阈值似乎不存在。

Chrome下的auto

这里的auto跟浏览器相关,在MDN上介绍到:Chrome treats this as optimizeSpeed.但是实测: 16px 最终的效果与optimizeLegibility,启用了连体。

如果不想使用连体: font-variant-ligatures: none

25px 最终的效果与optimizeLegibility,启用了连体。

[译]optimizeLegibility在移动端的性能

在对长页面使用 optimizeLegibility 时,移动设备上实际上存在严重的、有效的致命性能问题(例如 30 秒加载延迟或更长)。仅当您知道最大文本长度是多少时才应用它。(此外,避免将它用于 Android 客户端,至少在每个人仍在使用的旧版本上:启用此模式时,其字体渲染器通常会出现非常奇怪的错误。)

我使用 Instapaper 进行了一些测试,以确定近似的 optimizeLegibility 性能限制。例如,Instapaper for iOS 中的一篇 5,000 字的文章将仅在具有 A5 级或更高 CPU 的设备上使用 optimizeLegibility。为避免在较旧的 iOS 设备上出现问题,我不建议在任何长度超过 1,000 字的页面上盲目无条件地使用 optimizeLegibility。而且我根本不建议在 Android 上启用它。

There are actually significant, effectively fatal performance problems (such as 30-second loading delays, or longer) on mobile devices when using optimizeLegibility for long pages. Apply it only if you know what the maximum text length will be. (Also, avoid using it for Android clients, at least on the older versions that everyone still uses: its font renderer often has very strange bugs when this mode is enabled.)

I did some testing with Instapaper to determine approximate optimizeLegibility performance limits. A 5,000-word article in Instapaper for iOS, for instance, will only use optimizeLegibility on devices with an A5-class or greater CPU. To avoid problems on older iOS devices, I wouldn’t recommend using optimizeLegibility blindly and unconditionally on any pages longer than about 1,000 words. And I wouldn’t recommend enabling it on Android at all.

后记

在学习这个属性的时候参考了多篇文章。 对于20px阈值的问题,各篇文章都不太一样。 本文阈值问题仅为笔者测试结果。不代表官方意见。