CSS @font-face中设置的font-weight属性不生效该如何解决?
问题原因
你当前的写法存在两个核心错误:
- 同一字体家族的不同字重版本,你分别设置了不同的
font-family名称,浏览器无法识别这些字体属于同一系列,自然无法根据font-weight自动匹配对应的字体文件 - 你给TT Hoves Regular常规字体对应的
@font-face规则中,错误把font-weight设为了700(常规体正确值应为400),进一步导致权重匹配逻辑混乱
正确实现方案
1. 重写fonts.css的@font-face规则
同一字体家族所有字重统一使用相同的font-family名称,仅通过font-weight区分不同版本:
@font-face { font-family: "Password"; font-style: normal; font-weight: 400; src: url("~assets/fonts/password.woff2") format("woff2"), url("~assets/fonts/password.woff") format("woff"); } /* TT Hoves 系列全部统一font-family名称 */ @font-face { font-family: "TT Hoves"; font-style: normal; font-weight: 700; src: url("~assets/fonts/tt_hoves_bold-webfont.woff2") format("woff2"), url("~assets/fonts/tt_hoves_bold-webfont.woff") format("woff"); } @font-face { font-family: "TT Hoves"; font-style: normal; font-weight: 600; src: url("~assets/fonts/tt_hoves_demibold-webfont.woff2") format("woff2"), url("~assets/fonts/tt_hoves_demibold-webfont.woff") format("woff"); } @font-face { font-family: "TT Hoves"; font-style: normal; font-weight: 500; src: url("~assets/fonts/tt_hoves_medium-webfont.woff2") format("woff2"), url("~assets/fonts/tt_hoves_medium-webfont.woff") format("woff"); } /* 常规体font-weight修正为400,font-family和其他系列统一 */ @font-face { src: url("~assets/fonts/tt_hoves_regular-webfont.woff2") format("woff2"), url("~assets/fonts/tt_hoves_regular-webfont.woff") format("woff"); font-family: "TT Hoves"; font-style: normal; font-weight: 400; }
2. 元素样式调用
直接指定统一的字体家族名称,需要不同字重时单独设置font-weight即可,浏览器会自动匹配对应的字体文件:
/* 全局默认设置,不用每个元素重复写字体 */ body { font-family: "TT Hoves", sans-serif; font-weight: 400; /* 默认用常规体 */ } h2.text{ font-size: 1.125rem; /* 继承全局字体,需要加粗时单独指定font-weight即可 */ font-weight: 600; }
如果要使用700字重的粗体,直接设置font-weight:700就能自动调用对应字体文件,不需要再切换font-family值。
内容的提问来源于stack exchange,提问作者uneeb meer
相关产品推荐
相关产品推荐

