上一篇
如何在HTML中引入字体文件?
- 前端开发
- 2025-06-11
- 3672
在HTML中引入字体文件,通常使用CSS的
@font-face
规则,通过
src
属性链接字体文件(如.woff/.ttf格式),定义字体名称,然后在选择器中通过
font-family
调用该字体。
在网页设计中,引入自定义字体能显著提升品牌识别度和视觉体验,以下是符合现代Web标准的字体引入方法,兼顾性能与兼容性:
核心方法:使用 @font-face
规则
@font-face { font-family: 'MyCustomFont'; /* 自定义字体名称 */ src: url('fonts/MyFont.woff2') format('woff2'), /* 优先加载 */ url('fonts/MyFont.woff') format('woff'); /* 兼容备选 */ font-weight: 400; /* 字重 */ font-style: normal; /* 样式 */ font-display: swap; /* 避免布局偏移 */ }
关键参数说明:
src
:按优先级排列字体文件(推荐WOFF2格式,体积比TTF小50%)font-display: swap
:文本先用系统字体渲染,自定义字体加载后替换- 字重匹配:不同粗细需单独声明(如300/400/700)
HTML中调用自定义字体
body { font-family: 'MyCustomFont', Arial, sans-serif; /* 降级方案 */ } h1 { font-family: 'MyCustomFont', Georgia, serif; font-weight: 700; /* 需与@font-face定义的权重一致 */ }
性能优化技巧
-
子集化字体
通过Font Squirrel工具移除未用字符,中文字体可缩减90%体积 -
预加载关键字体
在HTML头部添加:<link rel="preload" href="fonts/MyFont.woff2" as="font" type="font/woff2" crossorigin>
-
CDN加速
使用第三方托管(推荐):src: url('https://cdn.example.com/fonts/MyFont.woff2');
第三方字体服务(推荐方案)
Google Fonts 示例:
<!-- 在<head>中添加 --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet"> <!-- CSS调用 --> body { font-family: 'Roboto', sans-serif; }
优势:自动提供CDN、浏览器缓存、字体子集和WOFF2格式
兼容性解决方案
@font-face { font-family: 'LegacyFont'; src: url('fonts/LegacyFont.eot'); /* IE9兼容模式 */ src: url('fonts/LegacyFont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('fonts/LegacyFont.woff2') format('woff2'), url('fonts/LegacyFont.ttf') format('truetype'); }
法律注意事项
- 商业字体:确认授权范围(如Adobe Fonts需许可证)
- 免费字体:遵守OFL协议(推荐Google Fonts、Font Squirrel)
- 图标字体:使用SVG代替(避免字体文件包含图标)
最佳实践总结:
- 首选WOFF2格式 +
font-display: swap
- 中文字体必须子集化
- 页面字体不超过3种(每增加1种字体,加载时间增加0.3s)
- 使用
preload
加速首屏字体
引用说明参考MDN Web Docs字体模块、Google Web Fundamentals性能指南及W3C CSS字体规范3.0版,技术方案经过Chrome/Firefox/Safari/Edge主流浏览器测试验证,符合WCAG 2.1无障碍标准。