Vue Material多语言应用中如何配置生效的中文字体?
如何在Vue Material构建的多语言应用中正确声明并使用中文字体?
我的当前配置
App.vue
本地加载Vue Material相关样式:
<script> import Vue from 'vue' import VueMaterial from 'vue-material' import 'vue-material/dist/vue-material.min.css' import 'vue-material/dist/theme/default.css' import './assets/material-icons.css' Vue.use(VueMaterial) // 其他代码... </script>
material-icons.css
我已经在这个文件顶部添加了针对Windows和macOS的中文字体规则:
@font-face { font-family: 'Microsoft Yahei', '微软雅黑', '宋体'; font-style: normal; font-weight: normal; src: local('Microsoft Yahei'), local('微软雅黑'); } @font-face { font-family: 'STXihei', '华文细黑', '宋体'; font-style: normal; font-weight: normal; src: local('STXihei'), local('华文细黑'); } @font-face { font-family: 'Material Icons'; font-style: normal; font-weight: 400; src: url(MaterialIcons-Regular.eot); /* For IE6-8 */ src: local('Material Icons'), local('MaterialIcons-Regular'), url(MaterialIcons-Regular.woff2) format('woff2'), url(MaterialIcons-Regular.woff) format('woff'), url(MaterialIcons-Regular.ttf) format('truetype'); } .material-icons { font-family: 'Material Icons'; font-weight: normal; font-style: normal; font-size: 24px; /* Preferred icon size */ display: inline-block; line-height: 1; text-transform: none; letter-spacing: normal; word-wrap: normal; white-space: nowrap; direction: ltr; /* Support for all WebKit browsers. */ -webkit-font-smoothing: antialiased; /* Support for Safari and Chrome. */ text-rendering: optimizeLegibility; /* Support for Firefox. */ -moz-osx-font-smoothing: grayscale; /* Support for IE. */ font-feature-settings: 'liga'; }
问题现象
我添加了包含中文的元素:
<div class="md-button-content">中文字</div>
但通过Firefox开发者工具检查发现,中文字体并没有被应用。请问该如何确保中文字体正常生效?
解决方案
你遇到的问题主要出在**@font-face的声明方式和全局字体族的配置**上,以下是具体的修复步骤:
1. 修正@font-face的错误声明
你现在的@font-face写法有问题:font-family属性只能指定一个字体名称,不能直接写多个字体作为备选。正确的做法是定义一个通用的字体族名称,然后在实际使用font-family时设置备选链。
修改material-icons.css中的中文字体声明:
/* 定义通用的中文字体族名称 */ @font-face { font-family: 'CustomChinese'; font-style: normal; font-weight: normal; src: local('Microsoft Yahei'), local('微软雅黑'), local('SimSun'); }
这里用
SimSun代替宋体的英文名称,兼容性更好;同时只保留一个@font-face声明,通过local()依次查找本地已安装的字体。
2. 全局设置字体族
Vue Material的默认样式会覆盖全局字体,所以需要在全局样式中强制设置中文元素的字体,或者覆盖Vue Material的主题字体,二选一即可:
方法一:添加全局字体样式
在material-icons.css末尾添加全局字体规则,确保所有Vue Material组件都能继承:
/* 全局应用中文字体,优先使用自定义中文字体族, fallback到系统默认中文字体 */ body, .md-button-content, [class^="md-"] { font-family: 'CustomChinese', 'Microsoft Yahei', '微软雅黑', 'SimSun', sans-serif; }
方法二:覆盖Vue Material的主题字体
如果你使用了Vue Material的主题系统,这种方式更符合框架设计规范:
// 在App.vue或者单独的主题配置文件中 Vue.material.theme.registerTheme('default', { primary: 'blue', accent: 'red', // 修改主题字体族 font: { family: 'CustomChinese, Microsoft Yahei, 微软雅黑, SimSun, sans-serif' } })
3. 验证生效
修改完成后重新启动项目,再通过Firefox开发者工具检查元素的font-family属性,就能看到我们设置的中文字体被优先应用了。
内容的提问来源于stack exchange,提问作者Hanxue
相关产品推荐
相关产品推荐

