@font-face 核心語法
@font-face 規則允許網頁載入伺服器端字體文件,打破「僅能使用用戶系統安裝字體」的限制,是 Web Font 技術的基石。
標準兼容寫法(Bulletproof 語法)
@font-face {
font-family: 'MyCustomFont'; /* 自定義字體名稱,供 font-family 引用 */
/* 1. EOT:IE 6-8 必需(放第一位,防止 IE9+ 誤載) */
src: url('fonts/MyCustomFont.eot'); /* IE9 兼容模式 */
src: url('fonts/MyCustomFont.eot?#iefix') format('embedded-opentype'); /* IE6-8 */
/* 2. WOFF2:現代瀏覽器首選(壓縮最好,體積最小) */
src: url('fonts/MyCustomFont.woff2') format('woff2');
/* 3. WOFF:現代瀏覽器廣泛支援 */
src: url('fonts/MyCustomFont.woff') format('woff');
/* 4. TTF/OTF:舊版 Safari、Android、iOS 備援 */
src: url('fonts/MyCustomFont.ttf') format('truetype');
/* src: url('fonts/MyCustomFont.otf') format('opentype'); */
/* 5. SVG:極舊 iOS (3.2-4.1) 備援,現已基本不用 */
/* src: url('fonts/MyCustomFont.svg#MyCustomFont') format('svg'); */
font-weight: normal; /* 正常粗細 */
font-style: normal; /* 正常樣式 */
font-display: swap; /* 關鍵:控制字體載入行為 */
}
字體格式兼容性對照表
| 格式 | MIME 類型 | 支援瀏覽器 | 壓縮率 | 優先級 |
| WOFF2 | font/woff2 | Chrome 36+、FF 39+、Safari 11+、Edge 14+ | ~30% 比 WOFF 更小 | 🥇 首選 |
| WOFF | font/woff | Chrome 5+、FF 3.6+、Safari 5.1+、IE 9+ | 標準壓縮 | 🥈 次選 |
| TTF/OTF | font/ttf | 舊版 Safari、Android 4.3-、iOS 4.2- | 無壓縮 | 🥉 備援 |
| EOT | application/vnd.ms-fontobject | IE 6-8 | 微軟專用壓縮 | IE 專用 |
| SVG | image/svg+xml | iOS 3.2-4.1 (已淘汰) | XML 文本 | ❌ 棄用 |
關鍵屬性:font-display
@font-face {
/* ... */
font-display: swap; /* 推薦值 */
}
| 值 | 行為 | 適用場景 |
auto | 瀏覽器預設(通常類似 block) | 一般情況 |
block | 阻塞期(~3s)顯示空白,載入後換字體 | 品牌字體必須顯示 |
swap | 立即顯示備用字體,載入後無縫切換 | ✅ 大多數情況推薦 |
fallback | 極短阻塞(~100ms)後用備用字體,載入後切換 | 體驗優先 |
optional | 僅在極快網路下載入,否則永久用備用字體 | 非關鍵裝飾字體 |
實際使用範例
<style>
@font-face {
font-family: 'C39HrP72DlTt';
src: url('C39HrP72DlTt.eot');
src: url('C39HrP72DlTt.eot?#iefix') format('embedded-opentype'),
url('C39HrP72DlTt.woff2') format('woff2'),
url('C39HrP72DlTt.woff') format('woff'),
url('C39HrP72DlTt.ttf') format('truetype');
font-weight: normal;
font-style: normal;
font-display: swap;
}
#bar {
font-size: 150px;
font-family: 'C39HrP72DlTt', sans-serif;
text-align: center;
}
</style>
<div id="bar">*china*</div>
字體獲取與子集化工具鏈
- 下載字體:Google Fonts、Font Squirrel、1001 Fonts、DaFont(注意授權)
- 格式轉換與子集化:
- 子集化策略:僅包含項目實際用到的字符(常用字 3000-6000),體積從 MB 級降至 20-80KB
中文字體特殊考量
- 中文字體檔案龐大(完整字集 5-20MB),必須子集化
- 動態子集化方案:fonttools + 服務端按需生成
- 靜態子集化:構建時根據頁面內容提取字符集
- 推薦開源中文 Web Font:
Noto Sans SC/TC、Source Han Sans、MiSans、HarmonyOS Sans
效能優化清單
- ✅ 優先 WOFF2,提供 WOFF 備援
- ✅ 設置
font-display: swap 避免 FOIT(字體不可見閃爍)
- ✅
<link rel="preload" as="font" crossorigin> 預載關鍵字體
- ✅ 字體文件啟用 HTTP/2 + 長期緩存 (
Cache-Control: max-age=31536000, immutable)
- ✅ 關鍵字體 Base64 內聯 CSS(極小字體,< 10KB)
- ✅ 使用
unicode-range 讓瀏覽器按需下載