制作css字体
自定义CSS字体的方法
使用@font-face规则引入自定义字体文件(如.woff、.ttf格式),定义字体族名称和文件路径:
@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:广泛支持的Web字体格式
- TTF/OTF:兼容性更好但文件较大 建议提供至少WOFF2和WOFF两种格式以兼顾兼容性。
应用自定义字体
在CSS选择器中通过font-family调用定义好的字体:
body {
font-family: 'MyCustomFont', sans-serif;
}
始终添加备用字体(如sans-serif)确保回退显示。
优化字体加载
使用font-display控制字体加载期间的渲染行为:
@font-face {
font-family: 'MyCustomFont';
src: url('font.woff2') format('woff2');
font-display: swap; /* 文本先用备用字体显示,自定义字体加载后替换 */
}
字体性能优化
- 子集化:通过工具移除未使用的字符(如Font Squirrel)
- 预加载:在HTML头部添加预加载提示
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>
可变字体(Variable Fonts)
使用单个文件支持多种字重/宽度变化:
@font-face {
font-family: 'VariableFont';
src: url('font.woff2') format('woff2-variations');
font-weight: 100 900; /* 定义支持的字重范围 */
font-stretch: 75% 125%; /* 定义支持的宽度范围 */
}
应用时可动态调整属性:
h1 {
font-family: 'VariableFont';
font-weight: 650;
font-stretch: 110%;
}






