@font-face 基礎語法
@font-face {
font-family: 'MyCustomFont'; /* 自訂字體名稱 */
src: url('font.woff2') format('woff2'),
url('font.woff') format('woff'),
url('font.ttf') format('truetype'),
url('font.eot'); /* IE9 以下相容 */
font-weight: 400; /* 對應字重 */
font-style: normal; /* 對應樣式 */
font-display: swap; /* 關鍵:載入策略 */
}
字體格式支援度與優先順序
| 格式 | MIME | 壓縮 | 支援度 | 建議順序 |
| WOFF2 | font/woff2 | 最佳 (比 WOFF 小 30%) | 所有現代瀏覽器 | 1 (優先) |
| WOFF | font/woff | 良好 | IE9+、所有現代 | 2 (備援) |
| TTF/OTF | font/ttf | 無壓縮 | 舊版 Android、iOS | 3 (最後備援) |
| EOT | application/vnd.ms-fontobject | 僅 IE | IE6–IE8 | 4 (僅 IE 專案需求) |
| SVG Font | image/svg+xml | — | 已棄用 | ❌ 不建議 |
font-display:關鍵載入策略
| 值 | 區塊期 | 交換期 | 行為 | 適用場景 |
auto | 瀏覽器決定 | 瀏覽器決定 | 預設,通常類似 block | 一般內文 |
block | ~3s | ∞ | 隱藏文字直到字體載入完成 | 關鍵品牌標題 |
swap | 0 | ∞ | 立即顯示備用字體,載入後替換 ⭐ 推薦 | 大多數內文、UI |
fallback | ~100ms | ~3s | 短暫隱藏,超時用備用字體 | 次要文字 |
optional | ~100ms | 0 | 極短嘗試,失敗永久用備用字體 | 非關鍵裝飾字體 |
完整實作範例
/* 1. 定義字體族群,按字重/樣式分組 */
@font-face {
font-family: 'Noto Sans TC';
src: url('/fonts/noto-sans-tc-v27-latin-ext-regular.woff2') format('woff2');
font-weight: 400;
font-style: normal;
font-display: swap;
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Noto Sans TC';
src: url('/fonts/noto-sans-tc-v27-latin-ext-700.woff2') format('woff2');
font-weight: 700;
font-style: normal;
font-display: swap;
unicode-range: /* 同前 */;
}
/* 2. 使用 */
body { font-family: 'Noto Sans TC', system-ui, sans-serif; }
效能優化關鍵點
- 子集化:移除未使用字符(工具:
pyftsubset、fonttools、Transfonter),中文字體可從 10MB+ 降至 200–500KB
- 預載入關鍵字體:
<link rel="preload" as="font" type="font/woff2" crossorigin href="/fonts/main.woff2">
- 自託管優於 CDN:避免 DNS 查詢、TLS 握手、第三方快取不可控
- 啟用 HTTP/2 或 HTTP/3:多路複用並行下載多字重
- 設定快取頭:
Cache-Control: public, max-age=31536000, immutable(檔名含 hash)
變數字體 - 現代趨勢
@font-face {
font-family: 'InterVariable';
src: url('Inter-Variable.woff2') format('woff2-variations');
font-weight: 100 900; /* 单一文件包含所有字重 */
font-display: swap;
}
單一檔案支援連續字重、斜體、寬度等軸向,大幅減少請求數與總體積。
常見問題排查
| 現象 | 可能原因 | 解決 |
| 字體不生效 | 路徑錯誤、CORS 限制、格式不支援 | 檢查 Network 面板、確認 Access-Control-Allow-Origin、優先用 WOFF2 |
| 閃爍/佈局位移 | 無 font-display: swap、備用字體度量差異大 | 加 font-display: swap、調整 size-advance/ascent-override (CSS Font Metrics API) |
| 中文缺字 | 字體不含該字符、unicode-range 設定錯誤 | 確認字體支援範圍、使用 fallback 字體鏈 |
| 加粗/斜體不生效 | 未定義對應 font-weight/font-style 的 @font-face | 每個字重樣式組合需獨立 @font-face 宣告 |