css 字体库制作
创建自定义 CSS 字体库
准备字体文件
确保拥有字体文件的合法使用权,常见格式包括 .woff、.woff2、.ttf 或 .otf。将字体文件放置在项目目录中,例如 fonts/ 文件夹。
定义 @font-face 规则
在 CSS 文件中使用 @font-face 声明自定义字体。指定字体家族名称、文件路径和格式类型:
@font-face {
font-family: 'CustomFont';
src: url('fonts/custom-font.woff2') format('woff2'),
url('fonts/custom-font.woff') format('woff');
font-weight: normal;
font-style: normal;
}
多字重和样式支持
若字体包含粗体或斜体变体,需为每个变体单独定义 @font-face 规则:
@font-face {
font-family: 'CustomFont';
src: url('fonts/custom-font-bold.woff2') format('woff2');
font-weight: bold;
font-style: normal;
}
优化加载性能
优先使用 woff2 格式(现代浏览器支持),并通过 font-display 控制渲染行为:
@font-face {
font-family: 'CustomFont';
src: url('fonts/custom-font.woff2') format('woff2');
font-display: swap;
}
应用自定义字体
在样式表中通过 font-family 属性调用定义好的字体:
body {
font-family: 'CustomFont', sans-serif;
}
高级字体库管理技巧
可变字体支持
若使用可变字体,需在 @font-face 中定义轴范围:
@font-face {
font-family: 'VariableFont';
src: url('fonts/variable-font.woff2') format('woff2-variations');
font-weight: 100 900;
font-stretch: 75% 125%;
}
unicode-range 优化 通过字符子集减少加载体积:
@font-face {
font-family: 'CustomFont';
src: url('fonts/latin-subset.woff2') format('woff2');
unicode-range: U+0000-00FF;
}
CDN 托管方案 考虑使用第三方字体托管服务(如 Google Fonts)的 CSS 引入方式:
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
字体特征设置 启用 OpenType 特性:
.text {
font-feature-settings: 'liga', 'kern';
font-variant-ligatures: common-ligatures;
}






