uniapp 字体设置
uniapp 字体设置方法
uniapp 中设置字体可以通过以下几种方式实现,适用于不同场景和需求。
全局字体设置
在 App.vue 文件中通过样式定义全局字体,确保所有页面继承该字体设置。

<style>
/* 设置全局默认字体 */
page {
font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}
</style>
局部字体设置
在单个页面或组件的 <style> 标签中定义局部字体样式。
<style scoped>
.custom-text {
font-family: "Helvetica Neue", Arial, sans-serif;
font-size: 16px;
font-weight: bold;
}
</style>
动态加载网络字体
通过 CSS 的 @font-face 规则加载自定义字体文件(如 .ttf 或 .woff 格式)。

<style>
@font-face {
font-family: 'CustomFont';
src: url('https://example.com/fonts/custom-font.ttf') format('truetype');
}
.custom-font {
font-family: 'CustomFont';
}
</style>
平台差异处理
针对不同平台(如小程序、H5)可能需要特殊处理字体设置。例如,小程序中需将字体文件放在本地目录并引用。
/* 小程序端 */
@font-face {
font-family: 'MiniProgramFont';
src: url('/static/fonts/mini-font.ttf');
}
使用条件编译
通过条件编译实现不同平台的字体设置差异。
/* #ifdef MP-WEIXIN */
page {
font-family: "WeChatFont", sans-serif;
}
/* #endif */
/* #ifdef H5 */
body {
font-family: "WebFont", Arial;
}
/* #endif */
注意事项
- 字体文件需放在
static目录下以确保正确引用。 - 部分平台(如小程序)对网络字体有限制,需提前测试兼容性。
- 中文字体文件较大,建议裁剪或使用系统默认字体优化性能。






