css 制作字库
使用CSS制作字库的方法
在CSS中制作字库通常涉及使用@font-face规则引入自定义字体文件。以下是具体实现方式:
准备字体文件
确保拥有字体文件的合法使用权,常见格式包括.ttf、.otf、.woff、.woff2。推荐使用.woff2格式,因其压缩率更高。
定义@font-face规则
在CSS文件中声明字体家族名称和文件路径:
@font-face {
font-family: 'MyCustomFont';
src: url('path/to/font.woff2') format('woff2'),
url('path/to/font.woff') format('woff');
font-weight: normal;
font-style: normal;
font-display: swap;
}
应用自定义字体
通过font-family属性将字体应用到元素:
body {
font-family: 'MyCustomFont', sans-serif;
}
优化字体加载的策略
预加载关键字体 在HTML头部添加预加载提示:
<link rel="preload" href="path/to/font.woff2" as="font" type="font/woff2" crossorigin>
使用font-display控制渲染
font-display: swap确保文本始终可见,字体加载完成后再替换。

子集化字体
通过工具如pyftsubset提取仅需的字符集,减少文件体积:
pyftsubset font.ttf --output-file=font-subset.woff2 --flavor=woff2 --text="ABCDE123"
动态加载字体的技巧
JavaScript控制加载 监听字体加载状态:
document.fonts.load('1em MyCustomFont').then(() => {
document.body.classList.add('fonts-loaded');
});
CSS变量备用方案 定义备用字体堆栈:

:root {
--main-font: 'MyCustomFont', system-ui, sans-serif;
}
body {
font-family: var(--main-font);
}
性能监控与调试
使用浏览器开发者工具 Chrome DevTools的"Fonts"面板可查看加载状态和渲染详情。
CLS指标优化
确保字体尺寸与备用字体相近,避免布局偏移。可通过size-adjust属性调整:
@font-face {
font-family: 'MyCustomFont-Fallback';
src: local('Arial');
size-adjust: 95%;
ascent-override: 90%;
}
跨浏览器兼容方案
多格式字体提供 按优先级提供多种格式:
@font-face {
font-family: 'MyCustomFont';
src: url('font.woff2') format('woff2'),
url('font.woff') format('woff'),
url('font.ttf') format('truetype');
}
IE兼容处理
对旧版IE需使用.eot格式:
@font-face {
font-family: 'MyCustomFont';
src: url('font.eot');
src: url('font.eot?#iefix') format('embedded-opentype'),
url('font.woff2') format('woff2');
}






