浏览器兼容性
1. 最深层兼容:
定义字体 @font-face
,并在其他样式文件之前引入。
@font-face {
font-family: 'MyWebFont';
src: url('webfont.eot'); /* IE9 Compat Modes */
src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
url('webfont.ttf') format('truetype'), /* Safari, Android, iOS */
url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}
使用字体:
body {
font-family: 'MyWebFont', Fallback, sans-serif;
}
2.更实用的方案:
由于 WOFF/WOFF2 格式的字体文件兼容性比较好,且加载起来相对较快,所以实际上我们可以只使用这两个格式:
@font-face {
font-family: 'MyWebFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff');
}
Google Fonts API
Google Fonts 使用起来很简单。搜到要用的字体,点击右上角的“Select this font”,就能下载、使用这个字体了。比如选择字体 Roboto:
image.png
如上图所示,只需要在
<head>
标签中嵌入链接https://fonts.googleapis.com/css?family=
的样式文件即可。比如 Roboto 对应的样式文件链接是 https://fonts.googleapis.com/css?family=Roboto&display=swap 。
关于此链接的参数说明,详看 Get Started with the Google Fonts API。
如果使用自己的服务器托管呢?
可以下载字体文件压缩包之后,利用转换工具,比如 Transfonter 生成对应的@font-face
样式文件。再把生成的字体文件和样式文件放到项目中即可。