MUI自定义Typography时fontSize显示NaNrem问题求助
MUI Typography H1 fontSize 显示NaNrem问题的解决方法
问题场景
在MUI的createTheme中配置typography.h1.fontSize为动态clamp表达式后:
createTheme({ typography:{ fontFamily: 'Circe, sans-serif', allVariants: { textTransform: 'unset', lineHeight: 1.2, }, h1: { fontWeight: 'bold', lineHeight: 1.14, fontSize: 'clamp(24px, calc(24px +(40 - 24)*((100vw - 768px) /(1920 - 768))), 40px)', }, fontWeightBold: 700, fontWeightMedium: 500, fontWeightRegular: 400, } });
出现以下问题:
- 元素检查器中显示
font-size: NaNrem,最终 fallback 到默认的2em - CSS变量
--mui-font-h1的取值是正确的,包含完整的clamp表达式
解决方法
方法1:通过styleOverrides直接设置样式
绕过MUI对typography.h1.fontSize的自动转换逻辑,在components配置中直接覆盖H1的字体大小:
createTheme({ typography: { fontFamily: 'Circe, sans-serif', allVariants: { textTransform: 'unset', lineHeight: 1.2, }, h1: { fontWeight: 'bold', lineHeight: 1.14, // 保留基础配置以确保CSS变量生成正确,可设置一个默认值 fontSize: '40px', }, fontWeightBold: 700, fontWeightMedium: 500, fontWeightRegular: 400, }, components: { MuiTypography: { styleOverrides: { h1: { fontSize: 'clamp(24px, calc(24px + (40 - 24) * ((100vw - 768px) / (1920 - 768))), 40px)', }, }, }, }, });
方法2:自定义pxToRem转换函数
修改MUI默认的单位转换逻辑,让它对包含clamp/calc的复杂表达式直接返回原值,不进行rem转换:
import { createTheme } from '@mui/material/styles'; const customPxToRem = (value) => { // 对复杂字符串表达式直接返回,不转换 if (typeof value === 'string' && (value.includes('clamp') || value.includes('calc'))) { return value; } // 常规数值按默认逻辑转rem return `${Number(value) / 16}rem`; }; const theme = createTheme({ typography: { fontFamily: 'Circe, sans-serif', allVariants: { textTransform: 'unset', lineHeight: 1.2, }, h1: { fontWeight: 'bold', lineHeight: 1.14, fontSize: 'clamp(24px, calc(24px +(40 - 24)*((100vw - 768px) /(1920 - 768))), 40px)', }, fontWeightBold: 700, fontWeightMedium: 500, fontWeightRegular: 400, }, }, { typography: { pxToRem: customPxToRem, }, });
问题原因
MUI内部会对typography配置中的fontSize执行pxToRem转换,该函数仅能处理简单的数值或带单位的单一值,无法解析clamp嵌套calc的复杂表达式,导致转换后生成NaNrem的错误值。而CSS变量--mui-font-h1是直接拼接原始配置值,因此显示正常。
内容的提问来源于stack exchange,提问作者legkiy
相关产品推荐
相关产品推荐

