css 制作字库
使用 CSS 制作字库
CSS 可以通过 @font-face 规则引入自定义字体,从而实现在网页中使用特定字库的效果。以下是实现方法:
1. 准备字体文件
确保拥有字体的合法使用权,并获取字体文件(通常为 .woff、.woff2、.ttf 或 .otf 格式)。推荐使用 .woff2 格式,因其压缩率高且兼容性较好。
2. 定义 @font-face 规则
在 CSS 文件中使用 @font-face 声明自定义字体,指定字体名称和文件路径:
@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:定义字体的名称,后续可通过该名称引用。src:指定字体文件路径及格式,按优先级排列。font-display: swap:确保文本始终可见,避免加载期间的空白。
3. 应用自定义字体
在需要使用的选择器中通过 font-family 引用定义的字体:
body {
font-family: 'MyCustomFont', sans-serif;
}
优化字体加载性能
使用本地字体回退
在 src 中添加 local() 检查用户是否已安装字体,减少网络请求:
@font-face {
font-family: 'MyCustomFont';
src: local('MyCustomFont'),
url('path/to/font.woff2') format('woff2');
}
子集化字体
通过工具(如 pyftsubset)裁剪字体文件,仅保留需要的字符集,减小文件体积。
处理多字重和样式
若字体包含多种字重(如粗体、斜体),需为每种样式单独定义 @font-face:
@font-face {
font-family: 'MyCustomFont';
src: url('path/to/font-regular.woff2') format('woff2');
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: 'MyCustomFont';
src: url('path/to/font-bold.woff2') format('woff2');
font-weight: 700;
font-style: normal;
}
兼容性注意事项
- 旧版浏览器可能需要
.ttf或.eot格式。 - 使用工具(如 Font Squirrel Generator)生成多格式字体文件。
- 测试不同浏览器的渲染效果,确保一致性。







