You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MUI Grid每行仅显示2个元素布局问题求助

解决MUI Grid每行显示2个元素的问题

你的问题核心是没有将每个产品项正确嵌套在Grid Item组件中,同时外层Grid的结构存在冲突。以下是具体修复方案:

1. 核心调整点

  • 移除Grid container上多余的item属性(原代码中<Grid container item xs={12} spacing={-1}>属于错误用法,container和item属性不应同时加在同一个Grid组件上)
  • 给每个循环生成的产品项套上Grid item xs={6},xs={6}意味着在最小屏幕下每行分配2个元素(MUI Grid采用12列布局,12/6=2)
  • 简化嵌套的Grid结构,避免多层container导致布局混乱

2. 修改后的完整代码

return (
  <div>
    <Grid container xs={12} spacing={2}>
      <h1> Uspar</h1>
      <Grid container spacing={2}>
        {PRODUCTS.map((item, index) => (
          <Grid item xs={6} key={index}>
            <Button className={classes.productItem}>
              <img className={classes.productImage} src={item.img} />
              <h1> {item.Title}</h1>
              <h2> {item.Subtitle}</h2>
              <Typography variant="body1">{item.description}</Typography>
            </Button>
          </Grid>
        ))}
      </Grid>
    </Grid>
  </div>
);

3. 额外注意事项

  • spacing属性建议使用正数(比如2),负数会导致元素重叠,影响布局效果
  • 如果需要在大屏设备上保持每行2个元素,无需额外设置,xs={6}会自动继承到更大尺寸的屏幕;若要在特定尺寸调整,可追加sm={6}、md={6}等属性

内容的提问来源于stack exchange,提问作者Mogly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:35:21