在 CSS 中使用 font-weight 更改“常规”字体是否会使其实际上变为粗体?(即另一个字体文件)

平面设计 网站设计 字体 css 字体粗细
2022-01-15 10:40:08

我是一名网络开发人员,我正在开发一个使用 Quicksand Light/Regular/Bold 作为字体的项目。Web 应用程序的标准字体是 Quicksand 常规字体,但也有更轻、更粗的文本。

作为一名网络开发人员,我通常会应用一个简单的 CSS 样式,如下所示:

font-weight: bold; // or 400, 600, 800

这是避免将字体设置为每个非“常规”元素的有效技巧吗?如果没有,是否有像这样工作的字体?(即通过 CSS 修改它们以获得不同的字体)

1个回答

网络字体

有 2 种方法可以使用@font-face. 第一个,可能也是最常见的(我相信大多数生成器,例如Font Squirrel会输出这个)是用自己唯一的家族名称定义每个字体文件(即每个粗细和样式)。

@font-face {
    font-family: 'YourFont';
    src: url('your_font.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}
@font-face {
    font-family: 'YourFontBold';
    src: url('your_font_bold.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}
@font-face {
    font-family: 'YourFontItalic';
    src: url('your_font_italic.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

请注意,每个上的font-weightandfont-style都设置为正常,并且每个都有一个唯一的font-family名称。这意味着,任何时候你设置 afont-weightfont-style任何非正常的东西,你都会得到浏览器实现的“人造”样式,而不是来自正确字体文件的样式。如果您不将默认浏览器 CSS 样式重置为“正常”,这也可能导致“双”粗体或斜体。例如:

strong {
    font-family: 'YourFontBold';
    }

在不font-weight将 重置为正常的情况下,由于浏览器正在加载粗体字体文件添加自己的假粗体样式,因为默认样式strongfont-weight: bold;.

更好的方法:

@font-face {
    font-family: 'YourFont';
    src: url('your_font.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}
@font-face {
    font-family: 'YourFont';
    src: url('your_font_bold.ttf') format('truetype');
    font-weight: 700;
    font-style: normal;
}
@font-face {
    font-family: 'YourFont';
    src: url('your_font_italic.ttf') format('truetype');
    font-weight: normal;
    font-style: italic;
}

注意字体文件的定义font-weightfont-style正确对应,并且都使用相同的font-family名称。以这种方式声明你的字体意味着你可以在你的 CSS 中的任何地方完全按照你的期望使用,并且你会得到正确的字体,没有“人造”样式font-weightfont-style

只有关键字“粗体”和“斜体”可能被所有浏览器理解,因此您应该使用特定的字体粗细数字。另请记住,浏览器通常不会很好地舍入字体粗细,因此请准确指定您想要的粗细,并确保它们与您的@font-face声明和 CSS 样式相匹配。

此方法的问题在于 Internet Explorer 8 或更低版本无法识别使用相同font-family名称的多个样式和权重。我相信这也会在旧版本的 iOS 中引起问题

Google Fonts通过有条件地仅使用常规字体提供 IE 8 或更低版本并让 IE “伪造”其他样式来解决此问题。不理想。

smasmingmagazine.com 上的这篇文章建议有条件地为 Internet Explorer 单独添加样式,这应该可以解决多个权重和样式的问题:

<link href="http://fonts.googleapis.com/css?family=Droid+Serif:400,400italic,700,700italic" rel="stylesheet" type="text/css">
<!--[if IE]>
<link href="http://fonts.googleapis.com/css?family=Droid+Serif" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Droid+Serif:400italic" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Droid+Serif:700" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Droid+Serif:700italic" rel="stylesheet" type="text/css">
<![endif]-->

因此,如果您想在 CSS 中使用font-weightfont-style而不用担心实际的字体名称,请不要依赖网络字体生成器并@font-face自己正确设置声明,并注意它会在旧浏览器中导致问题。

桌面字体

声明未嵌入使用@font-face的字体将仅使用安装在用户计算机上的字体。这些应该尊重任何font-weightfont-style样式并加载正确的字体(我在 OS X 上的 Chrome 和 Firefox 中的所有测试都按预期工作),但这可能取决于浏览器和操作系统,并且取决于字体文件本身中字体的命名——你无法真正控制的事情。