React项目@font-face为何需指定font-weight?字体不生效问题答疑
React项目中Noto Sans KR字体样式不生效问题解析
项目环境与初始配置
字体文件目录结构
- src assets Fonts - NotoSansKR-Bold.otf - NotoSansKR-DemiLight.otf - NotoSansKR-Medium.otf - NotoSansKR-Regular.otf
初始@font-face设置(App.css)
@font-face { font-family: 'Noto Sans KR-Bold'; src: url('./assets/Fonts/NotoSansKR-Bold.otf'); } @font-face { font-family: 'Noto Sans KR-Medium'; src: url('./assets/Fonts/NotoSansKR-Medium.otf'); } @font-face { font-family: 'Noto Sans KR-Regular'; src: url('./assets/Fonts/NotoSansKR-Regular.otf'); } @font-face { font-family: 'Noto Sans KR-DemiLight'; src: url('./assets/Fonts/NotoSansKR-DemiLight.otf'); }
组件中字体调用方式(styled-components)
const UserName = styled.div` margin-left: 6px; font-family: 'Noto Sans KR-Regular'; font-style: normal; font-size: 14px; line-height: 20px; color: #262e33; `;
遇到的问题
无论在font-family中指定Bold/Medium/Regular/DemiLight哪一个,页面显示的字体粗细完全一致,字体样式未生效。
可行解决方案
调整@font-face配置,将同系列字体归为同一个font-family,同时为每个字体文件指定对应的font-weight,字体即可正常显示不同粗细:
@font-face { font-family: 'Noto Sans CJK KR'; font-style: normal; font-weight: 100; src: url("styles/fonts/NotoSansKR-Light.woff2") format('woff2'), url("styles/fonts/NotoSansKR-Light.woff") format('woff'), url("styles/fonts/NotoSansKR-Light.otf") format('truetype') } @font-face { font-family: 'Noto Sans CJK KR'; font-style: normal; font-weight: normal; src: url("styles/fonts/NotoSansKR-Regular.woff2") format('woff2'), url("styles/fonts/NotoSansKR-Regular.woff") format('woff'), url("styles/fonts/NotoSansKR-Regular.otf") format('truetype') } @font-face { font-family: 'Noto Sans CJK KR'; font-style: normal; font-weight: 500; src: url("styles/fonts/NotoSansKR-Medium.woff2") format('woff2'), url("styles/fonts/NotoSansKR-Medium.woff") format('woff'), url("styles/fonts/NotoSansKR-Medium.otf") format('truetype') } @font-face { font-family: 'Noto Sans CJK KR'; font-style: normal; font-weight: bold; src: url("styles/fonts/NotoSansKR-Bold.woff2") format('woff2'), url("styles/fonts/NotoSansKR-Bold.woff") format('woff'), url("styles/fonts/NotoSansKR-Bold.otf") format('truetype') }
疑问解答
为什么要指定font-weight?
每个OTF文件确实对应不同粗细,但浏览器的字体匹配机制依赖font-family和font-weight的组合来选择字体文件。仅靠文件名或独立的font-family名称,浏览器无法识别文件对应的字重等级,只会按默认规则分配字重,导致无法区分不同粗细的字体。
初始配置的错误点
- 字体家族拆分不合理:你把每个粗细的字体定义成了独立的font-family,比如'Noto Sans KR-Bold'、'Noto Sans KR-Regular'。浏览器会为每个独立的font-family分配默认字重(通常为normal/400),即使文件名带Bold,浏览器也不会自动识别它是粗体,只会当作常规字重字体处理,最终所有显示效果趋同。
- 缺少字重映射关系:没有明确标注每个字体文件对应的font-weight,浏览器无法根据你需要的粗细匹配到对应的文件,只能使用默认的 fallback 字体或某一个版本,导致粗细无差异。
正确的做法是把同一系列的不同粗细字体归到同一个font-family下,通过不同的font-weight值映射到对应的文件,这样浏览器就能根据你设置的font-weight加载对应粗细的字体。
内容的提问来源于stack exchange,提问作者yjlee
相关产品推荐
相关产品推荐

