@font-face 自定义字体
什么是 @font-face
@font-face 规则允许网页设计师使用用户计算机上未安装的字体。
基本语法
@font-face {
font-family: "字体名称";
font-weight: 粗细;
src: url("字体文件路径") format("格式"),
url("字体文件路径") format("格式");
font-display: 显示方式;
}
字体格式
| 格式 | 扩展名 | 说明 |
|---|
| WOFF2 | .woff2 | 最新格式,压缩率最高 |
| WOFF | .woff | Web开放字体格式 |
| TTF | .ttf | TrueType字体 |
| OTF | .otf | OpenType字体 |
| EOT | .eot | IE专用 |
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@font-face 自定义字体</title>
<style>
body {
font-size: 40px;
}
/* 定义自定义字体 */
@font-face {
font-family: "阿里妈妈东方大楷 Regular";
font-weight: 400;
src: url("./webfont/AlimamaShuHeiTi-Bold.woff2") format("woff2"),
url("./webfont/AlimamaShuHeiTi-Bold.woff") format("woff");
font-variation-settings: normal;
font-display: swap;
}
/* 使用自定义字体 */
.regular {
font-family: "阿里妈妈东方大楷 Regular";
}
</style>
</head>
<body>
<div class="regular">是啥啊</div>
</body>
</html>
font-display 属性
| 值 | 说明 |
|---|
auto | 默认行为,浏览器决定 |
block | 短暂隐藏文本,字体加载完成后显示 |
swap | 立即显示后备字体,字体加载完成后替换 |
fallback | 短暂隐藏文本,超时后使用后备字体 |
optional | 短暂显示后备字体,字体加载快则替换 |
完整示例
@font-face {
/* 字体名称 */
font-family: "MyCustomFont";
/* 字体粗细 */
font-weight: 400;
/* 字体样式 */
font-style: normal;
/* 字体文件路径,多个格式作为后备 */
src: url("./fonts/myfont.woff2") format("woff2"),
url("./fonts/myfont.woff") format("woff"),
url("./fonts/myfont.ttf") format("truetype");
/* Unicode范围,可选 */
unicode-range: U+0020-007E;
/* 显示方式 */
font-display: swap;
}
/* 使用自定义字体 */
body {
font-family: "MyCustomFont", Arial, sans-serif;
}
多个字重定义
/* 常规字体 */
@font-face {
font-family: "MyFont";
font-weight: 400;
src: url("./myfont-regular.woff2") format("woff2");
}
/* 粗体 */
@font-face {
font-family: "MyFont";
font-weight: 700;
src: url("./myfont-bold.woff2") format("woff2");
}
/* 使用 */
.text-normal {
font-weight: 400;
font-family: "MyFont", Arial;
}
.text-bold {
font-weight: 700;
font-family: "MyFont", Arial;
}
字体图标
@font-face {
font-family: "iconfont";
src: url("./iconfont.woff2") format("woff2"),
url("./iconfont.woff") format("woff");
}
.icon {
font-family: "iconfont";
font-size: 20px;
}
/* 使用图标 */
<span class="icon"></span>
<span class="icon"></span>
常见字体资源
免费字体网站
中文字体
- 阿里巴巴普惠体: 免费商用
- 思源黑体: 免费开源
- 文泉驿微米黑: 免费开源
注意事项
- 字体文件大小: 网页字体会增加加载时间
- 版权问题: 使用字体时注意版权
- 兼容性: 考虑浏览器兼容性,提供多种格式
- 性能优化: 使用 WOFF2 格式,压缩率最高
学习要点
- 作用: 使用用户未安装的字体
- 格式: WOFF2 > WOFF > TTF
- 必须属性:
font-family, src - font-display: 推荐使用
swap - 后备: 提供多种格式作为后备