css 字体库制作
字体库制作方法
使用 @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;
}
字体格式选择
现代浏览器支持多种字体格式,推荐使用 .woff2 和 .woff 格式,它们具有更好的压缩率和兼容性。
- WOFF2:最优压缩,现代浏览器支持
- WOFF:广泛兼容,中等压缩
- TTF/OTF:兼容旧版浏览器,文件较大
字体文件转换
使用工具将 .ttf 或 .otf 转换为网页友好格式:
- 在线工具:Font Squirrel、Transfonter
- 命令行工具:
woff2_compress(Google 提供)
转换后生成多格式文件,确保跨浏览器兼容。
字体加载优化
使用 font-display 控制字体加载行为,避免布局偏移:
@font-face {
font-family: 'MyCustomFont';
src: url('font.woff2') format('woff2');
font-display: swap;
}
- swap:立即显示备用字体,自定义字体加载后替换
- block:短暂隐藏文本,直到字体加载完成
多字重和样式支持
为不同字重(如粗体、斜体)定义多个 @font-face 规则:
@font-face {
font-family: 'MyCustomFont';
src: url('font-regular.woff2') format('woff2');
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: 'MyCustomFont';
src: url('font-bold.woff2') format('woff2');
font-weight: 700;
font-style: normal;
}
本地字体回退
指定 local() 优先使用用户本地已安装的字体:
@font-face {
font-family: 'MyCustomFont';
src: local('Helvetica Neue'),
url('font.woff2') format('woff2');
}
性能考虑
- 子集化:使用工具提取仅需要的字符,减少文件大小
- 预加载:在 HTML 中提前加载关键字体
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>
浏览器兼容性
确保在旧版浏览器中提供备用字体堆栈:
body {
font-family: 'MyCustomFont', Arial, sans-serif;
}






