小编典典

如何使 MUI 中的组件居中并使其响应?

all

我不太了解 React Material-UI 网格系统。如果我想使用表单组件进行登录,在所有设备(移动设备和桌面设备)的屏幕上将其居中的最简单方法是什么?


阅读 142

收藏
2022-09-02

共1个答案

小编典典

因为您将在登录页面上使用它。这是我在使用 Material-UI 的登录页面中使用的代码

MUI v5

<Grid
  container
  spacing={0}
  direction="column"
  alignItems="center"
  justifyContent="center"
  style={{ minHeight: '100vh' }}
>

  <Grid item xs={3}>
   <LoginForm />
  </Grid>

</Grid>

MUI v4 及以下

<Grid
  container
  spacing={0}
  direction="column"
  alignItems="center"
  justify="center"
  style={{ minHeight: '100vh' }}
>

  <Grid item xs={3}>
    <LoginForm />
  </Grid>

</Grid>

这将使这个登录表单位于屏幕的中心。

但是,IE 仍然不支持 Material-UI Grid,您会在 IE 中看到一些错位的内容。

正如@max 所指出的,另一种选择是,

<Grid container justifyContent="center">
  <Your centered component/>
</Grid>

请注意,MUIv4 及以下版本应使用 justify=”center” 代替。

但是,使用没有 Grid 项的 Grid 容器是一种未记录的行为。

2022-06-06 更新

除此之外,另一种新的更好的方法是使用该Box组件。

<Box
  display="flex"
  justifyContent="center"
  alignItems="center"
  minHeight="100vh"
>
  <YourComponent/>
</Box>

这最初是由 Killian Huyghe 作为另一个答案发布的。

希望这会帮助你。

2022-09-02