CSS @font-face - “src: local('☺')” 是什么意思?

141

我第一次使用@font-face,从fontsquirrel下载了一个字体套件。

他们推荐我在CSS中插入的代码是:

@font-face {
    font-family: 'junctionregularRegular';
    src: url('Junction-webfont.eot');
    src: local('☺'), 
        url('Junction-webfont.woff') format('woff'), 
        url('Junction-webfont.ttf') format('truetype'), 
        url('Junction-webfont.svg#webfontoNEpZXy2') format('svg');
}

现在,笑脸的事情让我感到困惑。但是,src中的url数量也使我困惑 - 为什么他们建议使用这么多文件,当页面呈现时是否会将它们全部发送到浏览器?删除除.ttf之外的所有文件有什么危害吗?


@font-face的最后一个src属性在CSS级联中具有优先权,这意味着CSS将从底部到顶部进行解析。 - logu
2个回答

100
如果你阅读了Font Squirrel字体生成器中的注释,你会发现这是Paul Irish捉弄人的一个技巧。
以下是他博客文章的摘录:

And.. regarding @font-face syntax

I now recommend the bulletproof smiley variation over the original bulletproof syntax.

@font-face {
  font-family: 'Graublau Web';
  src: url('GraublauWeb.eot');
  src: local('☺'),
       url('GraublauWeb.woff') format('woff'), url('GraublauWeb.ttf') format('truetype');
}

From the bulletproof post:

Yes, it's a smiley face. The OpenType spec indicates any two-byte unicode characters won't work in a font name on Mac at all, so that lessens the likelihood that someone actually released a font with such a name.

There are a few reasons why smiley is a better solution:

  • Webkit+Font Management software can mess up local references, like turning glyphs into A blocks.

  • On OS X, Font Management software may alter system settings to show a dialog when trying to access a local() font that's accessible outside of Library/Fonts. More detail on my bulletproof post. Font Explorer X is also known to mess up other stuff in Firefox.

  • Although it's unlikely, you could reference a local() font which is completely different than what you think it is. (Typophile post on different fonts, same name) At the very least its a risk, and you're ceding control of the type to both the browser and host machine. This risk may not be worth the benefit of avoiding the font download.

These are all pretty edge case issues, but it's worth considering.


12
非常感谢☺,现在我明白了——我刚刚在nicewebtype.com发现了这篇文章,它回答了我所有其他的问题。 - stephenmurdoch
10
因此,本地代码的实质是“此字体在本地称为X”,我们使用笑脸图标来防止浏览器可能会使用同名但错误的字体(出于上述原因)。不错 :) - abelito
3
你是否真正需要一个 local() 语句?它是否多余?如果没有它,浏览器不应该使用你的第一个 url() 吗? - Simon East
当我在Chrome开发工具中查看我的CSS源代码时,笑脸会显示为这样:☺ 这是正确的吗? - Anthony
1
@Simon:本地语句是为了支持IE6-8(请参见链接的博客文章),因此,除非您不关心这些浏览器,否则需要它。 - Stijn de Witt
显示剩余2条评论

41

local(☺︎)是一种CSS hack,可以防止IE6-8下载无法使用的字体(它只能使用EOT格式的字体)。

解释:最后一个src属性优先级最高,这意味着CSS将从底部向上解析。 local(☺︎)将使IE跳过底部的src,而不会浪费带宽下载无法使用的字体,而是直接使用.eot格式的字体(在您问题中上一行中定义),以便使用它。笑脸只是为了确保没有一个名为该名称(字符组合)的本地字体。

更多信息请参见:http://nicewebtype.com/notes/2009/10/30/how-to-use-css-font-face/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接