【问题标题】:React MUI: How to make the css grid columns automatically wrap on the next rowReact MUI:如何使css网格列自动换行在下一行
【发布时间】:2022-01-17 04:59:24
【问题描述】:

我有一个 CSS 网格。它包含动态数量的元素。 像这样的:

 <Box className={classes.Grid}>
                <Button variant="outlined">1</Button>
                <Button variant="outlined">2</Button>
                <Button variant="outlined">3</Button>
                <Button variant="outlined">4</Button>
                <Button variant="outlined">5</Button>
                <Button variant="outlined">6</Button>
                <Button variant="outlined">7</Button>
                <Button variant="outlined">8</Button>
                <Button variant="outlined">9</Button>
                <Button variant="outlined">10</Button>
</Box>

const useStyles = makeStyles({
    Grid: {
        display: "grid",
        gridTemplateColumns: "repeat(3, 1fr)",
        gridGap: "10px",
        margin: "auto",
        width: "90vw",
    }
});

那么我怎样才能使每行上的 nr 列取决于网格元素的大小? 还忘了提到每个孩子都有特定的宽度/高度(220px/200px)

【问题讨论】:

  • “取决于网格元素的大小”是什么意思?例如,如果第一个按钮非常宽(这会使第一行只有一个项目并将其他项目推到下一行),您不想拥有三列?
  • 为什么不用Grid组件?

标签: css node.js reactjs material-ui


【解决方案1】:

您可能正在寻找自动填充。它会自动用可以容纳在该行中的尽可能多的元素填充行。 试试

gridTemplateColumns: "repeat(auto-fill, 5em)"

您可以根据需要调整 5em。

您可以将它与函数 minmax() 结合起来,仅定义按钮的最小尺寸,并让它们拉伸最后一位以填充整个宽度,而不仅仅是 n*button_width 增量。

gridTemplateColumens: "repeat(auto-fill, minmax(5em, 1fr))"

再次,将 5em 调整为按钮所需的最小宽度。

这是它的外观(在纯 HTML 中):

.grid{
  display: grid;
  gap: 1em;
  grid-template-columns: repeat(auto-fill, minmax(10em, 1fr));
}

.grid > div{
  width: 100%;
  text-align: center;
  background: grey;
}
<div class="grid">
<div>Element 1</div>
<div>Element 2</div>
<div>Element 3</div>
<div>Element 4</div>
<div>Element 5</div>
<div>Element 6</div>
<div>Element 7</div>
<div>Element 8</div>
<div>Element 9</div>
</div>

参考:https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns

【讨论】:

    【解决方案2】:

    如果您只想让行来填充可用空间,那么@robske_110's 答案就是您想要的。
    但是,如果您想更好地控制何时以及拥有多少大小,那么我建议您使用内置于MUIbreakpoints。 这是the sandbox link 和下面的示例。

    const useStyles = makeStyles((theme) =>
      createStyles({
        Grid: {
          display: "grid",
          gridTemplateColumns: "repeat(3, 1fr)",
          gridGap: "10px",
          margin: "auto",
          width: "90vw",
          [theme.breakpoints.down("sm")]: {
            gridTemplateColumns: "repeat(2, 1fr)"
          }
        }
      })
    );
    

    【讨论】:

    • 那么,我们可以使用 MUI 创建基于网格的组件,对吧?
    猜你喜欢
    • 2020-12-13
    • 1970-01-01
    • 2022-08-03
    • 2021-05-24
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 2019-09-06
    相关资源
    最近更新 更多