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

IT技术 reactjs authentication mobile material-ui desktop
2021-04-01 07:56:34

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

6个回答

因为您将在登录页面上使用它。这是我在使用 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 容器是一种未记录的行为。

希望这会帮助你。

通常, alignItems=center 和 justify=center 将组件放在页面的中心,但事实并非如此。添加 style={{ minHeight: '100vh' }} 可以完成这项工作,但它会在页面中添加一个滚动条。它将如何修复?
2021-05-28 07:56:34
谢谢。经过几个小时或搜索,最后这是帮助我在同一行中并排实现 FormLabel 和 TextField 的那个。
2021-06-12 07:56:34
@Slim 设置 CSS 正文边距:0
2021-06-16 07:56:34
MUI v5 开始,它是justifyContent="center"而不是justify="center"
2021-06-16 07:56:34
稍微修正一下,对于 Op 的用例,flex 方向应该是 row>>> direction="row"
2021-06-21 07:56:34

另一种选择是:

<Grid container justify = "center">
  <Your centered component/>
</Grid>
尽管这有效,但使用没有 Grid 项的 Grid 容器是一种未记录的行为,并且可能随时中断(尽管它可能不会)。
2021-05-29 07:56:34

您可以使用 Box 组件执行此操作:

import Box from "@material-ui/core/Box";

...

<Box
  display="flex"
  justifyContent="center"
  alignItems="center"
  minHeight="100vh"
>
  <YourComponent/>
</Box>
这是我最喜欢的答案,好技术
2021-06-05 07:56:34

这是没有网格的另一种选择:

<div
    style={{
        position: 'absolute', 
        left: '50%', 
        top: '50%',
        transform: 'translate(-50%, -50%)'
    }}
>
    <YourComponent/>
</div>
这个解决方案有一个问题,它将组件的尺寸在宽度和高度上缩短50%
2021-05-31 07:56:34
这对我将 Material-UI <Fab> 组件居中非常有效。作为附加,在 translate 方法中,第一个参数是水平平移,第二个参数是垂直平移。
2021-06-02 07:56:34

@Nadun 的版本对我不起作用,尺寸调整效果不佳。删除direction="column"或将其更改为row,有助于构建具有响应大小的垂直登录表单。

<Grid
  container
  spacing={0}
  alignItems="center"
  justify="center"
  style={{ minHeight: "100vh" }}
>
  <Grid item xs={6}></Grid>
</Grid>;