为什么字体名称需要引号?

据我所知,如果字体中包含空格,就需要使用双引号或单引号,比如:

font-family: "Times New Roman", Times;
font-family: 'Times New Roman', Times;

但在谷歌字体(http://www.google.com/webfont)上,我也看到

font-family: 'Margarine', cursive;

有些人甚至这样使用:

font-family: 'Margarine', 'Helvetica', arial;

我觉得这很奇怪,因为下面的方法同样有效:

font-family: Arial, Helvetica, sans-serif;
font-family: Cambria, serif;

那么在 CSS 中字体名称前后引号的正确用法是什么呢?

34315 次浏览

当字体名称中有空格时,必须使用引号。如果字体名称中没有空格,最好不要使用它们,尽管保留它们不会对文件大小造成任何影响。

例子:

font-family: "Times New Roman", Times; // ok, and best practice
font-family: Times New Roman, Times; // incorrect, Browser won't be able to find Times New Roman
font-family: "Times New Roman", "Times"; // ok, but has extraneous quotes around Times

我刚刚认识到这些引用并不是必须的,而是被推荐的。我们每天都在学习新的东西。

您还可以在 css 属性中看到它们,这些属性需要一个 url

background:url('hithere.jpg');
background:url(hithere.jpg);

这两种说法的效果是完全一样的。字体也是一样,在这种情况下,你使用哪种类型的引用是无关紧要的,只要你做事情的方式是一致的,这才是真正重要的。

您总是可以将特定的字体族名放在引号中,双引号或单引号,因此 Arial"Arial"'Arial'是等价的。只有 CSS 定义的通用字体家族名称(如 sans-serif)必须不加引号。

与流行的看法相反,由空格分隔的名称(如 Times New Roman)组成的字体名称不需要引用。但是,规格 建议“引用除连字符以外包含空格、数字或标点符号的字体族名”

有两个原因;

  1. 当实际的 font-family 名称与一般的 family 名称共享同一个名称时,为了避免与同名的关键字混淆,例如。

p {font-family: 'Shift', sans-serif;}

  1. 当字体中有一个以上的单词-姓氏,例如。

p {font-family: 'Times New Roman', ..... , a generic family name here ;}

何时引用 font-family:

可以选择

font-family: Times New Roman;         /* These are equivalent */
font-family: 'Times New Roman';
font-family: "Times New Roman";


font-family: Unique Ode™ 😊 Épopée;   /* These are equivalent */
font-family: "Unique Ode™ 😊 Épopée";


font-family: "Answer #42"             /* These are equivalent */
font-family: "Answer \23 42";
font-family: Answer \23 42;

只要字体名称只包含:

那么引号是可选的。单引号或双引号。忽略案件。有一些奇怪的边缘情况: 未引号的单词不能以数字、破折号或破折号开头。

必须的

font-family: "Intro Rust 2"           /* Unquoted words must not start with numbers. */
font-family: "Serif";                 /* For your own Serif, not the generic serif. */
font-family: "Yin/Yang";              /* Quote or code most ASCII punctuation. */

应该

font-family: "Initial Seals JNL"      /* `initial` and `default` are reserved words. */
font-family: "Omar Serif"             /* Generic names might also be reserved words? */

不可以

font-family: monospace;               /* Generic fonts must NOT be quoted. */
font-family: serif;
font-family: sans-serif;
font-family: cursive;
font-family: fantasy;

谢谢: