制作css字体
自定义CSS字体的方法
使用@font-face规则可以在CSS中引入自定义字体。该规则允许指定字体名称、源文件路径和格式,确保在不同浏览器中兼容。
@font-face {
font-family: 'MyCustomFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
字体文件格式的选择
现代浏览器优先支持WOFF2格式,因其压缩率更高。WOFF作为备选格式,适用于旧版浏览器。避免使用TTF或OTF直接嵌入网页,它们未针对网络优化。

body {
font-family: 'MyCustomFont', sans-serif;
}
通过Google Fonts快速引入
Google Fonts提供免托管的开源字体,直接通过<link>标签或CSS导入即可使用。例如引入Roboto字体:

<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
性能优化建议
使用font-display: swap确保文字在字体加载期间保持可读性。预加载关键字体资源加速渲染:
<link rel="preload" href="myfont.woff2" as="font" type="font/woff2" crossorigin>
可变字体的应用
可变字体通过调整轴参数实现多种字重和宽度变化,减少文件请求。定义时需声明可变轴范围:
@font-face {
font-family: 'VariableFont';
src: url('font.woff2') format('woff2-variations');
font-weight: 100 900;
font-stretch: 75% 125%;
}






