如何使用Material-UI(MUI)声明@font-face字体?
在Material-UI中使用GlobalStyles定义多个@font-face的解决方案
核心思路
Material-UI的GlobalStyles组件允许通过'@global'字段注入全局CSS规则。由于CSS本身支持为同一字体族声明多个不同字重/样式的@font-face变体,你可以将所有字体声明合并为一个CSS字符串,直接赋值给'@global'属性,避开样式对象属性唯一的限制。
完整实现代码
首先导入所需组件:
import { GlobalStyles } from '@mui/material'; import { createTheme, ThemeProvider } from '@mui/material/styles';
定义全局字体样式:
const globalFontStyles = { '@global': ` @font-face { font-family: 'Inter'; src: url('app/fonts/Inter-Regular.ttf') format('truetype'); font-weight: 400; font-style: normal; } @font-face { font-family: 'Inter'; src: url('app/fonts/Inter-Medium.ttf') format('truetype'); font-weight: 500; font-style: normal; } @font-face { font-family: 'Inter'; src: url('app/fonts/Inter-SemiBold.ttf') format('truetype'); font-weight: 600; font-style: normal; } @font-face { font-family: 'Inter'; src: url('app/fonts/Inter-Bold.ttf') format('truetype'); font-weight: 700; font-style: normal; } @font-face { font-family: 'Archivo'; src: url('app/fonts/Archivo-SemiBold.ttf') format('truetype'); font-weight: 600; font-style: normal; } ` };
创建主题并应用全局样式:
// 可选:设置全局默认字体 const theme = createTheme({ typography: { fontFamily: 'Inter, sans-serif', }, }); function App() { return ( <ThemeProvider theme={theme}> <GlobalStyles styles={globalFontStyles} /> {/* 你的应用组件内容 */} </ThemeProvider> ); } export default App;
说明
- 将所有
@font-face规则合并到一个字符串中,作为'@global'的值,既符合Material-UI的样式对象要求,又遵循CSS规范(同一字体族的多个变体声明是合法的)。 - 通过
createTheme设置typography.fontFamily可以让Material-UI组件默认使用你声明的字体,也可以在个别组件中通过sx或styled指定fontFamily: 'Archivo'来使用Archivo字体。
内容的提问来源于stack exchange,提问作者Mykyta Halchenko
相关产品推荐
相关产品推荐

