Por*_*o80 6 css font-face font-family google-fonts
这是我的问题:
为了提高我在 Google Speed Insight 上的速度标记,我必须从渲染阻止 Google 字体切换到本地加载的 Google 字体。
到目前为止一切都很好,除了我有一个巨大的问题。
在我以这种方式加载字体之前:
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700|Open+Sans+Condensed:300|Ubuntu+Condensed|Ubuntu:300,700" rel="stylesheet">
Run Code Online (Sandbox Code Playgroud)
在我巨大的样式表中,我只是正常地调用它们,例如:
body {
font-family: 'Open Sans', sans-serif;
font-weight: 400;
}
Run Code Online (Sandbox Code Playgroud)
但现在,由于我必须下载它们以避免渲染阻塞危险信号,所以我以这种方式调用它们:
@font-face {
font-family: "Opens Sans";
src: url("/fonts/OpenSans-Regular.ttf");
font-style: normal;
font-weight: 400;
}
@font-face {
font-family: "Opens Sans";
src: url("/fonts/OpenSans-Light.ttf");
font-weight: 300;
}
@font-face {
font-family: "Opens Sans";
src: url("/fonts/OpenSans-Bold.ttf");
font-weight: 600;
}
@font-face {
font-family: "Opens Sans";
src: url("/fonts/OpenSans-ExtraBold.ttf");
font-weight: 700;
}
@font-face {
font-family: "Opens Sans Condensed";
src: url("/fonts/OpenSansCondensed-Light.ttf");
font-weight: 300;
}
@font-face {
font-family: "Ubuntu Condensed";
src: url("/fonts/UbuntuCondensed-Regular.ttf");
font-weight: 300;
}
@font-face {
font-family: "Ubuntu";
src: url("/fonts/Ubuntu-Regular.ttf");
font-weight: 300;
}
@font-face {
font-family: "Ubuntu";
src: url("/fonts/Ubuntu-Bold.ttf");
font-weight: 700;
}
Run Code Online (Sandbox Code Playgroud)
在这里你可以看到我的问题。
我用相同的名称调用不同的字体,但它们具有不同的粗细。显然,我可以用不同的名称来调用它们,例如“Ubuntu Bold”,但随后我必须更改整个样式表,例如,我现在应该声明:
body {
font-family: 'Open Sans Normal', sans-serif;
// font-weight: 400; //
}
p {
font-family: 'Open Sans Bold', sans-serif;
// font-weight: 700; //
}
Run Code Online (Sandbox Code Playgroud)
本质上,不再有字体粗细,只有不同的字体系列名称来说明粗细。
我的问题有什么解决办法吗?
即使字体文件不同,您也不需要font-family为字体的每个变体设置不同的字体。您可以只设置一项font-family,并在不同的属性中指定不同的变体@font-face。
您应该@font-face使用相同的font-family名称定义每个,如下所示:
@font-face {
font-family: 'Opens Sans';
src: url("/fonts/OpenSans-Regular.ttf");
font-style: normal;
font-weight: 400;
}
@font-face {
font-family: 'Opens Sans';
src: url("/fonts/OpenSans-Italic.ttf");
font-style: italic;
font-weight: 400;
}
@font-face {
font-family: 'Opens Sans';
src: url("/fonts/OpenSans-Bold.ttf");
font-style: normal;
font-weight: 600;
}
Run Code Online (Sandbox Code Playgroud)
请注意,每个不同的字体文件都有一个单独的@font-face与特定字体文件相对应的不同属性,但它们具有相同的font-family. 然后你可以在 css 中使用该字体,如下所示:
body {
font-family: 'Open Sans', sans-serif;
font-weight: 400;
}
.bold {
font-family: 'Open Sans', sans-serif;
font-weight: 600;
}
.italic {
font-family: 'Open Sans', sans-serif;
font-style: italic;
}
Run Code Online (Sandbox Code Playgroud)
css 类中的其他属性(font-weight、font-style等)将决定@font-face使用哪个属性。