css字体制作
使用 @font-face 自定义字体
通过 @font-face 规则引入自定义字体文件(如 .woff, .woff2, .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;
}
定义后可通过 font-family: 'MyCustomFont' 调用。
优化字体加载性能
使用 preload 提前加载关键字体,避免渲染阻塞:
<link rel="preload" href="path/to/font.woff2" as="font" type="font/woff2" crossorigin>
结合 font-display: swap 确保文本始终可见:
@font-face {
font-family: 'MyCustomFont';
src: url('path/to/font.woff2') format('woff2');
font-display: swap;
}
使用变量管理字体族
CSS 变量简化多字体场景的维护:
:root {
--main-font: 'MyCustomFont', sans-serif;
--code-font: monospace;
}
body {
font-family: var(--main-font);
}
pre {
font-family: var(--code-font);
}
调整字体渲染细节
通过属性微调视觉效果:
font-smoothing改善抗锯齿(仅 macOS):body { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }letter-spacing控制字符间距:h1 { letter-spacing: 0.05em; }
响应式字体大小
使用 clamp() 实现视口自适应字号:
p {
font-size: clamp(1rem, 2vw, 1.5rem);
}
或通过媒体查询分段调整:
@media (max-width: 768px) {
body {
font-size: 14px;
}
}






