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

Material-UI Grid组件无间距问题求助

解决Material-UI Grid组件无间距的问题

嘿,我一眼就揪出你问题的关键啦!你的Grid组件始终没有间距,核心原因是子Grid元素缺少item属性——Material-UI的Grid布局规则里,container的spacing属性只会作用于带有item属性的子Grid元素上。

先看你原来的代码:

<Grid container spacing={40} justify="center">
  <Grid> {/* 这里缺少item属性 */}
    <Card>
      <Typography component='h4' variant='h4'>Manager Login</Typography>
      <Button>Login</Button>
    </Card>
  </Grid>
  <Grid> {/* 这里也缺少item属性 */}
    <Card>
      <Typography component='h4' variant='h4'>User Login</Typography>
      <Button>Login</Button>
    </Card>
  </Grid>
</Grid>

只需要给每个子Grid加上item属性,就能让spacing正常生效了,修正后的代码如下:

<Grid container spacing={40} justify="center">
  <Grid item> {/* 添加item属性 */}
    <Card>
      <Typography component='h4' variant='h4'>Manager Login</Typography>
      <Button>Login</Button>
    </Card>
  </Grid>
  <Grid item> {/* 添加item属性 */}
    <Card>
      <Typography component='h4' variant='h4'>User Login</Typography>
      <Button>Login</Button>
    </Card>
  </Grid>
</Grid>

补充说明:

  • 如果你用的是Material-UI v5版本,spacing的取值范围是1到12(对应8px的倍数);v4版本支持数值型px值(比如你代码里的40),但不管哪个版本,item属性都是启用间距的必要条件。
  • container组件的spacing是通过给子item元素添加内边距(padding)来实现间距的,没有item属性的子元素不会触发这个样式逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:06:18