如何替换本地Roboto字体为Google Fonts CDN并解决引入失效问题
失效核心原因
- 你当前使用的
@import仅引入了Roboto Slab的100字重,缺少你需要的Roboto 400/500/600字重、Roboto Slab 400字重 - 原有自定义的@font-face规则中font-family命名为「roboto regular」这类自定义名称,和Google Fonts返回的标准字体名不匹配,自然无法生效
修复操作步骤
- 替换原有@import语句,引入全部需要的字体资源,代码如下:
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;600&family=Roboto+Slab:wght@400&display=swap');
- 删除你当前写的全部自定义@font-face规则,Google Fonts会自动注入对应字体的@font-face声明,不需要自行定义。
- 全局替换你项目CSS中使用的字体名称,对应关系如下:
- 原
font-family: 'roboto regular'→ 替换为font-family: 'Roboto', sans-serif; font-weight: 400; - 原
font-family: 'roboto medium'→ 替换为font-family: 'Roboto', sans-serif; font-weight: 500; - 原
font-family: 'roboto bold'→ 替换为font-family: 'Roboto', sans-serif; font-weight: 600; - 原
font-family: 'roboto slab regular'→ 替换为font-family: 'Roboto Slab', serif; font-weight: 400;
引入规则里自带的
display=swap已经实现了字体 fallback 优化,比你原来设置的font-display: auto性能表现更好,不需要额外调整。
内容的提问来源于stack exchange,提问作者JuniorDev
相关产品推荐
相关产品推荐

