MUI 中的响应式排版?

Responsive Typography in MUI?

移动设计的标题字体通常较小。

MUI 是否有使排版响应的机制?

我看到默认主题的字体大小以 rems 为单位定义 - 这是否意味着只是减少基数 font-size 的问题? (这似乎不起作用,如果你想以不同的比例减少标题字体怎么办)。

更新

最新版MaterialUI(v4)全面支持响应式排版。有关详细信息,请参阅 official documentation

原答案

从版本 1.x 开始,Material UI 没有处理响应式排版的特定机制。

如您所述,您可以通过更改 <html> 元素的 font-size 来缩放所有 MUI Typography 的大小。 (docs)

const styles = theme => ({
  "@global": {
    html: {
      [theme.breakpoints.up("sm")]: {
        fontSize: 18
      }
    }
  }
}

主题覆盖

据我所知,唯一的其他选择是使用主题覆盖为每个 Typography 变体定义自定义样式。

这需要复制 createTypography.js 中的一些逻辑(即设置行高以保持垂直节奏)

const theme = createMuiTheme({
  overrides: {
    MuiTypography: {
      headline: {
        fontSize: pxToRem(24),
        [breakpoints.up("md")]: {
          fontSize: pxToRem(32)
        }
      }
    }
  }

更新

MUI v4 内置响应式排版!查看 here 了解详情。

旧回复

@Luke's 太棒了。我想添加一些细节来使这项工作在实践中进行,因为 breakpointspxToRem 都可以在主题对象上访问...使它成为先有鸡还是先有蛋的问题!我的做法:

import { createMuiTheme } from "@material-ui/core"

const defaultTheme = createMuiTheme({ ... customisations that don’t rely on theme properties... })
const { breakpoints, typography: { pxToRem } } = defaultTheme

const theme = {
  ...defaultTheme,
  overrides: {
    MuiTypography: {
      h1: {
        fontSize: "5rem",
        [breakpoints.down("xs")]: {
          fontSize: "3rem"
        }
      }
    }
  }
}

export default theme

如所述in the docs,您可以使用 responsiveFontSizes() 助手使主题中的排版字体大小响应。

import { createMuiTheme, responsiveFontSizes } from '@material-ui/core/styles';

let theme = createMuiTheme();
theme = responsiveFontSizes(theme);

MUI v5 添加了 sx prop to all MUI components which supports responsive values ,您可以在其中传递对象以定义不同断点处的值:

<Typography
  sx={{
    fontSize: {
      lg: 30,
      md: 20,
      sm: 15,
      xs: 10
    }
  }}
>
  This text is resized on different screen breakpoints
</Typography>

Box类似,Typography也支持system properties所以可以跳过sx属性,直接传fontSize属性 .下面的代码和上面一样,只是写的稍微短了一点:

<Typography
  fontSize={{
    lg: 30,
    md: 20,
    sm: 15,
    xs: 10
  }}
>
  This text is resized on different screen breakpoints
</Typography>

None 的其他答案使用 variant 预设。

MUI v5 的最佳方式,并使用variant:

<Typography sx={{ typography: { sm: 'body1', xs: 'body2' } }} >
    Hello world!
</Typography>

这似乎对我有用 v5

在App.js

...

import {
  createTheme,
  responsiveFontSizes,
  ThemeProvider,
} from '@mui/material/styles';

let theme = createTheme();
theme = responsiveFontSizes(theme);

...

function App() {
  return (
    <ThemeProvider theme={theme}>
      <Router>
       .....
      </Router>
    </ThemeProvider>
  );
}

“要自动执行此设置,您可以使用 responsiveFontSizes() 帮助程序使主题中的排版字体大小响应。” https://mui.com/customization/typography/#responsive-font-sizes

我使用 v5 的方法

import { createTheme } from "@mui/material";

let theme = createTheme({
  // ...
});

theme = createTheme(theme, {
  typography: {
    h1: {
      fontSize: 53,
      [theme.breakpoints.only("sm")]: {
        fontSize: 71,
      },
    },
  },
});
export default theme;