如何使用CSS引入.ttf格式的字体?

217

我想在我的页面上使用全局字体。我下载了一个.ttf文件,并将其包含在我的CSS中,但我的字体没有改变。

这是我的代码:

@font-face {
    font-family: 'oswald';
    src: url('/font/oswald.regular.ttf');
}

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
    margin:0;
    padding:0;
    border:0;
    font-size:100%;
    font:inherit;
    font-family: oswald;
    vertical-align:baseline
} 

我哪里做错了?


1
请您在浏览器控制台中检查网络选项卡,以确保字体已正确加载? - rink.attendant.6
这里获取woff。 - Mr. Alien
也许你应该尝试使用托管版本:https://www.google.com/fonts/specimen/Oswald - 并非所有浏览器都支持TrueType字体。 - Tieson T.
发布时的TTF字体浏览器支持便捷链接 https://caniuse.com/ttf,98.4%的浏览器支持。 - Matthew Lock
5个回答

314

仅提供.ttf文件的网络字体可能无法良好地支持跨浏览器。目前最佳的组合方案是使用以下组合:

@font-face {
    font-family: 'MyWebFont';
    src: url('webfont.eot'); /* IE9 Compat Modes */
    src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
         url('webfont.woff') format('woff'), /* Modern Browsers */
         url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
         url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

这段代码假定您已经有了.eot、.woff、.ttf和svg格式的网络字体。为了自动化整个过程,您可以使用:Transfonter.org

此外,现代浏览器正在向.woff字体转移,因此您也可以这样做:

@font-face {
    font-family: 'MyWebFont';
    src: url('myfont.woff') format('woff'), /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
         url('myfont.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5, Opera 10+, Safari 3—5 */
}  

阅读更多信息:http://css-tricks.com/snippets/css/using-font-face/


查看浏览器支持情况:Can I Use fontface


如果您正在使用GFonts,请查看https://dev59.com/1F8f5IYBdhLWcg3wHfk_#30585464 - Samie Bencherif
1
对于像我这样容易混淆的人来说——路径是使用正斜杠的 url('path/to/font.woff') - wunth
我在font-face规则中遇到了注释问题。将注释移到规则末尾解决了这个问题。 - Eric D'Souza
据我所知,没有理由同时使用“woff”和“ttf”,因为除了“woff”包含压缩之外,它们的格式都是相同的,而所有支持“ttf”的浏览器也支持“woff”。请选择其中一个即可。 - Abhi Beckert
我只有EOT格式的字体文件,而tranfosrter.org的使用方法是“点击添加字体按钮,选择您计算机上的TTF、OTF、WOFF、WOFF2或SVG字体文件,然后点击转换。” - Konrad Grzyb
显示剩余2条评论

61

28

您可以像这样使用字体:

@font-face {
  font-family:"Name-Of-Font";
  src: url("yourfont.ttf") format("truetype");
}

18

我知道这是一篇旧帖子,但这解决了我的问题。

@font-face{
  font-family: "Font Name";
  src: url("../fonts/font-name.ttf") format("truetype");
}

请注意 src:url("../fonts/font-name.ttf");,我们使用两个点返回到根目录,然后进入字体文件夹或您的文件所在位置。

希望这能帮助到一些人:) 开心编码!


2

检查控制台以确保资源已加载。根据文件和文件夹结构,您的URL可能会出错。请注意以下两者之间的区别:

src: url('/VT323/VT323-Regular.ttf') format('truetype');

src: url('VT323/VT323-Regular.ttf') format('truetype');

src: url('../VT323/VT323-Regular.ttf') format('truetype');

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