为什么@font面在我的样式表中失败?



我想在我的样式表中指定一个自定义字体。我可以让字体在我的 html 标头的链接语句中工作,但我宁愿把它放在我的样式表中。当我取消注释链接语句时,它可以工作。这是我的 html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Font Bug</title>
<link rel="stylesheet" href="fontBug.css">
<!--  <link href='https://fonts.googleapis.com/css?family=Metamorphous' rel='stylesheet'>-->
</head>
<body>
<p>This is normal text. It should display in a sans-serif font in black against white.</p>
<p class="customFont">This text should use the custom serif font, in a custom color</p>
<p>When I uncomment the link line inside the head tag of the html file, the 
font works. I don't understand why it doesn't work from the style sheet.
I know it's using the style sheet because I get the custom colors.
</p>
</body>
</html>

这是我.css文件:

@font-face {
font-family: Metamorphous;
// I have tried it both with and without the format specifier.
src: url(https://fonts.googleapis.com/css?family=Metamorphous) format("truetype");
}
.customFont {
font-family: Metamorphous, Sans-Serif;
background-color: #294575;
color: #6291D8;
}
body {
font-family: Sans-Serif;
font-size: 24px;
}

我认为您可能在样式表中以错误的方式实现了它。尝试替换

@font-face {
font-family: Metamorphous;
// I have tried it both with and without the format specifier.
src: url(https://fonts.googleapis.com/css?family=Metamorphous) format("truetype");
}

@import url('https://fonts.googleapis.com/css2?family=Metamorphous&display=swap');
h1 {
font-family: 'Metamorphous', cursive;
}

这似乎有效

@import url('https://fonts.googleapis.com/css2?family=Metamorphous&display=swap');
h1 {
font-family: 'Metamorphous', cursive;
}
<h1> Test </h1>

>@font面用于导入您自行设计的字体。

但是Metamorphous是一种Web安全字体,可以使用其他人已经说过的方法导入。

我的问题是我误解了url()函数的含义。我以为它是网络上资源的 URL,但实际上是本地文件的路径。事实证明,font-face 实际上是针对安装在服务器上的字体,而不是通过 URL 访问的。人们一直告诉我这是针对"自行设计的字体"的。 这包括但不限于您设计的字体。我没有设计字体,但我将其下载到我的开发环境中,并将字体 url 设置为该文件的相对路径(相对于.css文件(,然后它开始工作。我不知道他们为什么称它为 url 函数,但替代方案 local(( 显然适用于本地计算机中安装的字体。感谢回答的两个人。他们的回答引导我找到了这个解决方案。

最新更新