@font-face 自定义字体

学习

@font-face 自定义字体

2026-02-23/0/ 编辑


@font-face 自定义字体

什么是 @font-face

@font-face 规则允许网页设计师使用用户计算机上未安装的字体。

基本语法

@font-face {
  font-family: "字体名称";
  font-weight: 粗细;
  src: url("字体文件路径") format("格式"),
       url("字体文件路径") format("格式");
  font-display: 显示方式;
}

字体格式

格式扩展名说明
WOFF2.woff2最新格式,压缩率最高
WOFF.woffWeb开放字体格式
TTF.ttfTrueType字体
OTF.otfOpenType字体
EOT.eotIE专用

示例代码

<!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>

常见字体资源

免费字体网站

中文字体

  • 阿里巴巴普惠体: 免费商用
  • 思源黑体: 免费开源
  • 文泉驿微米黑: 免费开源

注意事项

  1. 字体文件大小: 网页字体会增加加载时间
  2. 版权问题: 使用字体时注意版权
  3. 兼容性: 考虑浏览器兼容性,提供多种格式
  4. 性能优化: 使用 WOFF2 格式,压缩率最高

学习要点

  1. 作用: 使用用户未安装的字体
  2. 格式: WOFF2 > WOFF > TTF
  3. 必须属性: font-family, src
  4. font-display: 推荐使用 swap
  5. 后备: 提供多种格式作为后备