CSS字体未找到时默认回退为Times New Roman,如何自定义回退规则
解决方案
- 配置全局字体 fallback 栈,避免兜底到Times New Roman
首先需要给全局设置完整的字体优先级列表,不要只写单个字体,末尾补通用无衬线字体sans-serif作为最后兜底,完全避免出现Times New Roman这类衬线默认字体。
你可以在全局CSS文件中添加如下规则::root { --font-primary: 'brandon-grotesque', sans-serif; } /* 让所有元素默认继承父级字体设置,消除input、button等元素的默认字体影响 */ * { font-family: inherit; } body { font-family: var(--font-primary); margin: 0; } - 统一Material UI主题的字体配置
MUI的<Typography>组件默认会读取主题内的typography.fontFamily配置,你需要把它和全局字体栈对齐,避免MUI组件单独走默认字体:
配置完成后把import { createTheme, ThemeProvider } from '@mui/material/styles'; const muiTheme = createTheme({ typography: { fontFamily: 'var(--font-primary)', // 直接复用全局CSS变量,保持配置统一 }, });<ThemeProvider>包裹在应用根组件外层即可生效。 - 避免拼写错误的优化方案
你之前尝试的font-family: 'my-font', inherit确实不符合CSS规范,font-family列表中不能直接写inherit关键字,你可以换成复用全局CSS变量作为兜底:
如果你担心手写字体名容易拼错,可以统一用Next.js内置的字体方案管理,直接生成字体变量,不需要手动写字体名字符串:.custom-element { /* 自定义字体找不到时,自动回退到全局定义的品牌字体 */ font-family: 'my-custom-font', var(--font-primary); }// Next.js 13+ App Router 写法,Pages Router同理可配置 import localFont from 'next/font/local'; const brandonFont = localFont({ src: [ { path: '../public/fonts/brandon-grotesque-regular.woff2', weight: '400' }, // 按需添加其他字重、样式的字体文件 ], variable: '--font-brandon', }); export default function RootLayout({ children }) { return ( <html lang="zh-CN" className={brandonFont.variable}> <body style={{ fontFamily: 'var(--font-brandon), sans-serif' }}> <ThemeProvider theme={muiTheme}> {children} </ThemeProvider> </body> </html> ); } - 兜底方案:拼写错误的别名映射
如果已经有多处拼写错误来不及逐一修改,可以用@font-face把常见的拼写错误别名指向正确的字体文件:@font-face { font-family: 'brandon-grotesk'; /* 常见错误拼写 */ src: url('/fonts/brandon-grotesque-regular.woff2') format('woff2'); weight: 400; style: normal; }
内容的提问来源于stack exchange,提问作者Kim Vu
相关产品推荐
相关产品推荐

