自定义字体不生效的根本原因是@font-face与tailwind.config.js命名、路径、顺序或配置方式不一致:必须用extend.fontFamily而非theme.fontFamily覆盖,默认字体族才会保留;@font-face须置于@tailwind base前且路径相对CSS文件;字体名大小写、引号、空格须完全一致;font-display: swap和format()为必选项。
自定义字体不生效,基本不是字体文件或浏览器问题,而是 @font-face 和 tailwind.config.js 两头没对齐——名字、路径、顺序、配置方式任一环节出错,Tailwind 就会静默回退到系统默认字体,控制台还不报错。
因为你直接写了 theme.fontFamily,而不是 theme.extend.fontFamily。Tailwind v3 的默认字体族(sans、serif、mono)只存在于初始 theme 中;一旦你用 fontFamily: { sans: [...] } 覆盖整个对象,这些键就彻底消失。结果是:font-sans 这个类还在 HTML 里,但编译后 CSS 根本没有对应规则。
extend: { fontFamily: { sans: ['"Inter"', 'ui-sans-serif', 'sans-serif'] } }
extend: { fontFamily: { heading: ['"Clash Display"', 'serif'] } } → 对应类名是 font-heading
fontFamily: { heading: ['"Clash Display"', 'serif'] } → 会清空所有默认族@font-face 必须出现在项目主 CSS 入口文件(如 src/styles.css)中,且严格位于 @tailwind base 之前。否则 Tailwind 的基础重置会干扰字体继承,浏览器也读不到注册信息。
@font-face → @tailwind base → @tailwind components → @tailwind utilities
src/styles.css,字体在 public/fonts/roboto.woff2,就得写 url("../public/fonts/roboto.woff2")
woff2,看是否 404;404 地址就是你该修正的路径字体名是字符串字面量匹配,不是模糊识别。@font-face 里写的 font-family: "Zilla Slab",配置里就必须写 '"Zilla Slab"'(单引号包裹双引号),大小写、空格、引号类型一个都不能差。
立即学习“前端免费学习笔记(深入)”;
@font-face 写 "roboto-mono",配置写 robotoMono → 不匹配'roboto-mono')→ PostCSS 解析失败,该条目被跳过'"Source Sans Pro"'、'"IBM Plex Sans"'
不是可选,是必加项。漏掉 font-display: swap 会导致 FOIT(Flash of Invisible Text),用户看到空白再闪现文字;漏掉 format("woff2") 会让某些浏览器忽略该字体源,尤其在使用本地 TTF/OTF 时更明显。
@font-face { font-family: "robotoMono"; src: url("../fonts/robotoMono.woff2") format("woff2"); font-display: swap; }
font-display: swap 必须写在 @font-face 块内,不能放在外部规则里最常被忽略的其实是“两头命名一致性”——@font-face 的 font-family 值和 tailwind.config.js 里 extend.fontFamily 的键名,必须逐字符相同。这不是约定,是硬性字符串比对。哪怕多一个空格,字体就永远卡在 fallback 上。