CSS 自定义字体 @font-face
学习@font-face · 难度:进阶 · +15XP
CSS 自定义字体 @font-face
@font-face 允许网页使用自定义字体,突破浏览器默认字体的限制。通过它可以在网页中嵌入任意 TrueType、OpenType、WOFF 等格式的字体文件,极大丰富网页的视觉表现力。
基本语法
@font-face {
font-family: 'MyFont'; /* 自定义字体的名称 */
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff'),
url('myfont.ttf') format('truetype');
font-weight: normal;
font-style: normal;
font-display: swap;
}
字体格式与兼容性
| 格式 | 扩展名 | 说明 |
|---|---|---|
| WOFF2 | .woff2 | 最佳压缩率,现代浏览器首选 |
| WOFF | .woff | 广泛支持,兼容性好 |
| TrueType | .ttf | 老旧格式,文件较大 |
| OpenType | .otf | 支持高级排版特性 |
| EOT | .eot | 仅 IE 旧版,已淘汰 |
font-display 策略
控制在字体加载期间文字的显示方式,对用户体验至关重要:
| 值 | 行为 | 适用场景 |
|---|---|---|
auto | 浏览器默认行为 | 一般情况 |
block | 短时间白屏后回退,加载完切换 | 字体对品牌很重要 |
swap | 立即显示回退字体,加载后切换(推荐) | 内容可读性优先 |
fallback | 短时间白屏,如加载慢则保持回退 | 性能优先 |
optional | 短时间白屏,如不立即可用则放弃 | 性能要求极高 |
@font-face {
font-family: 'BodyFont';
src: url('body.woff2') format('woff2');
font-display: swap; /* 先显示回退字体再替换 */
unicode-range: U+4E00-9FFF; /* 仅中文字符使用此字体 */
}
多字重字体
@font-face {
font-family: 'MyFont';
src: url('myfont-light.woff2') format('woff2');
font-weight: 300;
font-style: normal;
}
@font-face {
font-family: 'MyFont';
src: url('myfont-regular.woff2') format('woff2');
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: 'MyFont';
src: url('myfont-bold.woff2') format('woff2');
font-weight: 700;
font-style: normal;
}
/* 和普通字体一样使用 */
body { font-family: 'MyFont', sans-serif; }
h1 { font-weight: 700; } /* 自动使用 bold 版本 */
unicode-range 字符子集
限制字体使用的字符范围,减少不必要的字体下载:
/* 仅数字使用此字体 */
@font-face {
font-family: 'NumberFont';
src: url('numbers.woff2') format('woff2');
unicode-range: U+30-39;
font-display: swap;
}
/* 仅中文字符使用 */
@font-face {
font-family: 'ChineseFont';
src: url('chinese.woff2') format('woff2');
unicode-range: U+4E00-9FFF, U+3400-4DBF;
}
可变字体(Variable Fonts)
@font-face {
font-family: 'VariableFont';
src: url('variable.woff2') format('woff2-variations');
font-weight: 100 900; /* 支持的字重范围 */
font-stretch: 75% 125%; /* 支持的宽度范围 */
font-style: normal;
}
/* 使用精细字重 */
h1 { font-weight: 573; } /* 任意值! */
Google Fonts 使用
/* HTML 中引入 */
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC&display=swap" rel="stylesheet">
/* CSS 中使用 */
body {
font-family: 'Noto Sans SC', sans-serif;
}
性能建议
- 优先使用 WOFF2:压缩率最高,文件最小
- 使用
font-display: swap:确保文字在字体下载期间可见 - 预加载关键字体:
<link rel="preload" href="font.woff2" as="font" crossorigin> - 使用
unicode-range:按字符集拆分字体文件 - 使用子集化:中文字体仅包含需要的字符
- 考虑系统字体方案:如果不需要自定义字体,系统字体栈最快
系统字体栈(无需下载)
/* 现代系统字体栈 */
body {
font-family:
-apple-system, BlinkMacSystemFont,
"Segoe UI", Roboto, "Helvetica Neue",
Arial, "Noto Sans SC", sans-serif;
}
@font-face 是网页排版的基础工具。正确使用自定义字体能大幅提升品牌识别度和视觉品质,但需要平衡美观与加载性能。