Skip to content

自定义字体不 加载

快速摘要

你的自定义字体是 不加载因为字体 file path 是错误, 格式是 不正确, or 字体-face declaration 有错误.

为什么发生

  • 错误 URL path 到字体 file in src 属性

  • Missing or 不正确字体-格式 declaration

  • 字体 file 是不 deployed or 是 in 错误 directory

  • CORS issues 当加载字体从 不同领域

最小示例

✗ 错误代码
@font-face {
  font-family: 'MyFont';
  src: url('/fonts/myfont.ttf'); /* Wrong path or format */
}
body { font-family: 'MyFont'; }
✓ 修复代码
@font-face {
  font-family: 'MyFont';
  src: url('/fonts/myfont.woff2') format('woff2'),
       url('/fonts/myfont.woff') format('woff');
  font-display: swap;
}
body { font-family: 'MyFont', sans-serif; }

Fix 字体 path, use modern woff2 格式使用 woff fallback, 添加字体-display: swap for better 加载 behavior, and 包含 fallback 字体.

如何诊断

  • 检查 Network tab for 404 错误 on 字体 files

  • 验证 @字体-face src URL matches 实际 file 位置

  • 检查浏览器 console for CORS 错误 on 字体 files

  • Inspect computed 字体-family — 是你的自定义字体 listed?

如何修复

  • 正确 src URL path 到字体 file

  • 添加正确格式() 提示: 格式('woff2'), 格式('woff'), etc.

  • 添加 CORS 请求头如果加载字体从 CDN or 不同原点

  • Use fallback 字体 stack: 字体-family: 'MyFont', sans-serif

如何预防

  • Use Google 字体 or 字体 CDN 到 avoid path and 格式 issues

  • Preload 关键字体: <链接 rel='preload' href='字体.woff2' as='字体' 类型='字体/woff2' crossorigin>

  • 总是 specify fallback 字体 in 字体-family stack

相关资源

相关术语

相关课程

  • CSS

    学习 CSS 包含字体.

← 返回语言