【问题标题】:React Material UI Grid Horizontally Align Items for Containers With Different Number of ItemsReact Material UI Grid 水平对齐具有不同项目数的容器的项目
【发布时间】:2021-11-20 20:40:00
【问题描述】:

我正在使用 React Material UI 网格系统来对齐页面上的元素,该页面内部使用了弹性框。

一切都很好,但是当容器包含不同数量的项目时,我无法弄清楚如何水平对齐项目。

在下面的example 中,我有 2 个容器项,每个项的宽度为 6。第一个包含项目x1x2,第二个容器包含项目y1y2y3。如您所见,它现在的样子有点奇怪。我希望x1y1 水平对齐,x2y2 也是如此。

之所以将x1x2 放在第一个容器中,将y1y2y3 放在第二个容器中,是因为它们在语义上属于同一类。因此,我可以给外部容器不同的xssmmdlgxl 值,如果它到达断点,它们仍然会以正确的顺序显示。

但是,如果我只是将它们放在 3 行中,每行 2 列,它们将按照 x1y1x2y2、...的顺序中断。这显然是不对的。

因此,我的问题是,如何水平对齐它们?

编辑:

这就是现在的样子:

这是它想要的样子:

【问题讨论】:

    标签: html css reactjs flexbox material-ui


    【解决方案1】:

    我们希望向<Grid> 添加道具以使这成为可能。

    1. alignItems="flex-start" 将允许网格项目粘在顶部然后落到底部。
    2. direction="column" 在某种意义上会改变物品“堆叠”的流程。这将改变容器和它所附加的项目的大小,因此预计一些xs={12} 会变成xs={6},反之亦然。

    这是下面的示例代码以及通过沙箱实现的代码。

    import "./styles.css";
    import { Grid } from "@material-ui/core";
    
    export default function App() {
      return (
        <div className="App">
          <Grid alignItems="flex-start" container spacing={1}>
            <Grid container direction="column" item xs={6} spacing={1}>
              <Grid item xs={12} style={{ border: "1px solid black" }}>
                x1
              </Grid>
              <Grid item xs={12} style={{ border: "1px solid black" }}>
                x2
              </Grid>
            </Grid>
            <Grid container direction="column" item xs={6} spacing={1}>
              <Grid item xs={12} style={{ border: "1px solid black" }}>
                y1
              </Grid>
              <Grid item xs={12} style={{ border: "1px solid black" }}>
                y2
              </Grid>
              <Grid item xs={12} style={{ border: "1px solid black" }}>
                y3
              </Grid>
            </Grid>
          </Grid>
        </div>
      );
    }
    

    【讨论】:

    • 是的,这正是我需要的!非常感谢。
    猜你喜欢
    • 2019-10-17
    • 2020-11-02
    • 1970-01-01
    • 2020-05-05
    • 2021-05-24
    • 2020-08-17
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多