自托管Google Fonts(Montserrat)无法显示的问题求助
自托管Montserrat字体无法正常显示的问题
我尝试自托管从Google Fonts下载的Montserrat字体,跟着教程操作后还是无法正常显示。以下是我的配置:
我的style.css
@font-face { font-family: 'Montserrat'; font-style: normal; font-weight: 400; src: url('/fonts/montserrat-v25-latin-regular.eot'); /* IE9 Compat Modes */ src: local(''), url('/fonts/montserrat-v25-latin-regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('/fonts/montserrat-v25-latin-regular.woff2') format('woff2'), /* Super Modern Browsers */ url('/fonts/montserrat-v25-latin-regular.woff') format('woff'), /* Modern Browsers */ url('/fonts/montserrat-v25-latin-regular.ttf') format('truetype'), /* Safari, Android, iOS */ url('/fonts/montserrat-v25-latin-regular.svg#Montserrat') format('svg'); /* Legacy iOS */ } div { font-family: 'Montserrat', sans-serif; }
我试过直接通过URL加载字体,也用<link>标签做了preload,但都没成功。
我的HTML头部
<link rel="preload" href="/fonts/montserrat-v25-latin-regular.woff" as="font" type="font/woff" crossorigin> <link rel="preload" href="/fonts/montserrat-v25-latin-regular.eot" as="font" type="font/eot" crossorigin> <link rel="preload" href="/fonts/montserrat-v25-latin-regular.svg" as="font" type="font/svg" crossorigin> <link rel="preload" href="/fonts/montserrat-v25-latin-regular.ttf" as="font" type="font/ttf" crossorigin> <link rel="preload" href="/fonts/montserrat-v25-latin-regular.woff2" as="font" type="font/woff2" crossorigin>
请问我遗漏了什么?
排查步骤和解决方案
核对字体文件路径
确认fonts文件夹的实际位置和CSS里的路径匹配:- 如果
style.css在css子文件夹,路径要写成../fonts/xxx; - 如果是根目录下的
fonts文件夹,绝对路径没问题,但要确保服务器允许访问该目录(比如Apache/Nginx的配置没限制)。
- 如果
验证字体文件有效性
直接在浏览器地址栏输入字体文件的URL(比如http://你的域名/fonts/montserrat-v25-latin-regular.woff2),能下载或预览说明文件没问题;如果返回404,就是路径错误或文件缺失。修正preload的属性错误
SVG字体的type属性应该是image/svg+xml,不是font/svg;而且EOT属于过时格式,没必要preload。可以简化成:<link rel="preload" href="/fonts/montserrat-v25-latin-regular.woff2" as="font" type="font/woff2" crossorigin> <link rel="preload" href="/fonts/montserrat-v25-latin-regular.woff" as="font" type="font/woff" crossorigin>注意:preload只是提前加载,不会自动关联
@font-face,核心还是要保证CSS规则正确。查看浏览器控制台报错
按F12打开开发者工具,切换到「网络」标签:- 404状态:修正路径;
- CORS错误:检查服务器是否配置了CORS头(同域自托管一般不会有这个问题);
- 200状态但字体不生效:检查
@font-face的font-family名称和CSS引用是否完全一致,或者有没有其他CSS规则覆盖了div的字体设置。
简化@font-face规则
现代浏览器只需要woff2格式就能正常显示,先简化规则排除干扰:@font-face { font-family: 'Montserrat'; font-style: normal; font-weight: 400; src: url('/fonts/montserrat-v25-latin-regular.woff2') format('woff2'); font-display: swap; /* 可选,避免页面空白等待字体加载 */ }添加font-display属性
加上font-display: swap;可以让浏览器先显示备用字体,等自定义字体加载完成后再替换,避免出现“字体不显示”的错觉。
内容的提问来源于stack exchange,提问作者Don2
相关产品推荐
相关产品推荐

