瀏覽器兼容性
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.更實(shí)用的方案:
由于 WOFF/WOFF2 格式的字體文件兼容性比較好,且加載起來相對(duì)較快,所以實(shí)際上我們可以只使用這兩個(gè)格式:
@font-face {
font-family: 'MyWebFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff');
}
Google Fonts API
Google Fonts 使用起來很簡單。搜到要用的字體,點(diǎn)擊右上角的“Select this font”,就能下載、使用這個(gè)字體了。比如選擇字體 Roboto:

image.png
如上圖所示,只需要在
<head>標(biāo)簽中嵌入鏈接https://fonts.googleapis.com/css?family=的樣式文件即可。比如 Roboto 對(duì)應(yīng)的樣式文件鏈接是 https://fonts.googleapis.com/css?family=Roboto&display=swap 。
關(guān)于此鏈接的參數(shù)說明,詳看 Get Started with the Google Fonts API。
如果使用自己的服務(wù)器托管呢?
可以下載字體文件壓縮包之后,利用轉(zhuǎn)換工具,比如 Transfonter 生成對(duì)應(yīng)的@font-face 樣式文件。再把生成的字體文件和樣式文件放到項(xiàng)目中即可。