Google 本地不同粗细但名称相同的字体

Google font locally with different weights but with the same name

这是我的问题:

为了提高 google 速度洞察力上的 SPEED 标记,我不得不从渲染阻塞 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">

并且在我的巨大风格中-sheet,我只是正常地打电话给他们例如:

body {
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
}

但是现在,由于我必须下载它们以避免渲染阻塞红旗,所以我这样称呼它们:

@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;
}

在这里你可以看到我的问题。

我把不同的字体叫同一个名字,但是粗细不同。显然,我可以用不同的名称来称呼它们,例如 "Ubuntu Bold" 但是我必须改变我的整个样式 sheet,例如,我现在应该声明:

body {
      font-family: 'Open Sans Normal', sans-serif;
      // font-weight: 400; //
}
p {
      font-family: 'Open Sans Bold', sans-serif;
      // font-weight: 700; //
}

基本上,不再有字体粗细,只有不同的字体系列名称来说明粗细。

我的问题有解决办法吗?

即使字体文件不同,您也不需要为每个字体变体设置不同的 font-family。您可以只设置一个 font-family,并在不同的 @font-face 属性中指定不同的变体。

您应该使用相同的 font-family 名称定义每个 @font-face,如下所示:

@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;
}

请注意,每个不同的字体文件都有一个单独的 @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;
}

您 css 类 中的其他属性(font-weightfont-style 等)将决定使用哪个 @font-face