【问题标题】:How to horizontally center an item in MUI Grid item?如何在 MUI Grid 项目中水平居中项目?
【发布时间】:2019-02-20 18:52:45
【问题描述】:

如何在 MUI Grid 项目中居中元素?这是我的 React 应用程序中的一个 sn-p:

<Grid container>
  <Grid item xs={4}>
    // Unrelated stuff here
  </Grid>
  <Grid item xs={4}>
    // How do I centre these items?
    <IconButton className={classes.menuButton} color="inherit">
      <EditIcon/>
    </IconButton>
    <IconButton className={classes.menuButton} color="inherit">
      <CheckBoxIcon/>
    </IconButton>
  </Grid>
  <Grid item xs={4}>
    // Unrelated stuff here
  </Grid>
</Grid>

我尝试应用alignContentjustifyalignItems(对父&lt;Grid item&gt;)没有成功。

我认为这会很简单,但我没有找到任何关于在网格项目中居中项目的信息。

【问题讨论】:

    标签: css reactjs material-ui


    【解决方案1】:

    MUI v5中,根据migration guideGridjustify属性被重命名为justifyContent以与CSS属性名称对齐:

    <Grid container justifyContent="center" alignItems="center">
    

    【讨论】:

      【解决方案2】:
       <Grid container  className = {classes.root} align = "center" justify = "center" alignItems = "center"  >
                  <CssBaseline/>
                  <Grid item xs = {false} sm = {4} md = {6}>
      
                  </Grid>
                  <Grid item xs = {12} sm = {4} md = {6}>
      
                  </Grid>
              </Grid>`enter code here`
      

      【讨论】:

      • 谢谢,align="center" 属性为我工作。为什么这不在文档上? material-ui.com/api/grid
      • align="center" 完成了这项工作。文档对于 material-ui 来说可能非常糟糕......
      • align="center" 也为我工作。谢谢
      • align 属性不是 Material UI 属性。它只是 HTML。它只是将align="center" 添加到输出HTML。 &lt;Grid container item justify="center"&gt; 的解决方案是 Material UI 的正确惯用方法。
      【解决方案3】:

      这是正确的方法:

      <Grid container item xs={4} justify="center">
      

      如果容器属性设置为 true,组件将具有 flex 容器行为。

      Grid API

      【讨论】:

        【解决方案4】:

        两秒钟后...我通过一些简单的 CSS 解决了这个问题:

        <Grid item xs={4} style={{textAlign: "center"}}>
        </Grid>
        

        如果有另一种方法更“正确”,请随时发布另一个答案。

        【讨论】:

        • 这是完全正确的,因为元素是内联的(或内联块),所以居中是由 text-align 完成的
        • 如果你想在项目网格中居中一个按钮,这就是方式
        猜你喜欢
        • 2018-08-16
        • 2016-06-25
        • 1970-01-01
        • 2019-07-02
        • 1970-01-01
        • 1970-01-01
        • 2022-01-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多