CSS3 @font-face 規則讓網頁不再受限於系統預設字體,可載入自定義字體文件,實現獨特視覺設計。本文詳細介紹語法、格式兼容性與實戰工具鏈。
@font-face {
font-family: 'YourWebFontName'; /* 自定義字體名稱 */
src: url('font.woff2') format('woff2'),
url('font.woff') format('woff'),
url('font.ttf') format('truetype'),
url('font.eot') format('embedded-opentype');
font-weight: normal;
font-style: normal;
}
| 格式 | 副檔名 | 支援瀏覽器 | 備註 |
|---|---|---|---|
| WOFF2 | .woff2 | 現代瀏覽器(Chrome 36+、Firefox 39+、Edge 14+、Safari 12+) | 壓縮率最佳,首選格式 |
| WOFF | .woff | IE9+、Firefox 3.5+、Chrome 6+、Safari 5.1+、Opera 11.1+ | 廣泛兼容的標準格式 |
| TrueType | .ttf | IE9+、Firefox 3.5+、Chrome 4+、Safari 3+、Opera 10+、iOS 4.2+ | 未壓縮,文件較大 |
| EOT | .eot | IE4+ | 僅 IE 支援,舊版 IE 必備 |
| SVG | .svg | Chrome 4+、Safari 3.1+、Opera 10+、iOS 3.2+ | 舊版 iOS 必備,現代項目可省略 |
@font-face {
font-family: 'MyCustomFont';
/* 1. 現代瀏覽器優先載入 WOFF2 */
src: url('font.woff2') format('woff2'),
/* 2. 廣泛兼容 WOFF */
url('font.woff') format('woff'),
/* 3. 舊版瀏覽器回退 TTF */
url('font.ttf') format('truetype'),
/* 4. IE6-IE8 專用 EOT */
url('font.eot?#iefix') format('embedded-opentype');
font-weight: normal;
font-style: normal;
font-display: swap; /* 關鍵:避免字體載入期間文字不可見 */
}

<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>body {
font-family: 'MyCustomFont', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}