在CSS中使用@font-face添加本地ttf字体

11

我正在尝试为我测试的网站添加本地字体。它叫做“AcrosstheRoad.ttf”,可以在我的assets/fonts/文件夹中找到。我正在尝试使用以下代码将其读入CSS文件:

@font-face {
  font-family: 'AcrosstheRoad';
  src: url('assets/fonts/AcrosstheRoad.ttf')  format('truetype');
}

我希望将它用作某种标题类型,因此我正在使用

h3{
font-family: 'AcrosstheRoad';
color: #333;
}

但不幸的是,字体没有加载进来。有人知道我做错了什么吗?

谢谢! Christina

1个回答

18

assets前面添加一个斜杠:

(('/assets/fonts/AcrosstheRoad.ttf'))

这可能是问题,也可能不是问题,这取决于你的CSS文件在哪里以及你的网站结构如何。

如果上述方法不起作用,请将字体转换为.woff2.woff(尝试使用此工具:http://www.fontsquirrel.com/tools/webfont-generator)。这样做的原因是因为有些浏览器非常挑剔。将你的CSS更改为:

@font-face {
  font-family: 'AcrosstheRoad';
  src:  url('/assets/fonts/AcrosstheRoad.woff2') format('woff2'),
        url('/assets/fonts/AcrosstheRoad.woff') format('woff');,
       url('/assets/fonts/AcrosstheRoad.ttf') format('truetype');
}

您好,谢谢您的回复。我已经转换并更改了斜线,但恐怕它仍没有使用正确的字体。我在 /assets/fonts/ 目录中有 ttf、woff 和 woff2 文件,并使用以下代码调用:@font-face { font-family: 'AcrosstheRoad'; src: url('/assets/fonts/AcrosstheRoad.woff2') format('woff2'), url('/assets/fonts/AcrosstheRoad.woff') format('woff'), url('/assets/fonts/AcrosstheRoad.ttf') format('truetype'); } h3{ font-family: 'AcrosstheRoad'; color: #333; } - Christina
2
@Christina - Bill是正确的,你的路径有问题,如果你的css文件在assets/css/whatever.css中,那么你可以通过将字体的路径设置为../fonts/AcrosstheRoad.ttf来纠正问题。 - Adam Jenkins
首先,让我们搞清楚斜杠的问题。你的文件在 http://something.tld/assets/fonts/AcrosstheRoad.ext 吗? - Katherine
1
@Adam 哎呀!我把路径放在了索引文件而不是CSS文件夹,你完全正确!我感到很傻!但现在我的字体可以工作了,谢谢你的帮助! - Christina

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接