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

Material UI中如何让两个图表在各自Grid网格内居中?

问题原因

两个并排图表不居中、灰色背景分布不均,核心是三点配置问题:

  • lg断点下Grid容器总列数设为16,但两个图表项各占7.3列,总占用宽度仅14.6列,剩余1.4列的空白默认全部堆在右侧,导致整体偏左
  • sm断点下Grid总列数设为2,但单个图表项占4列,列宽配置溢出,小屏布局计算逻辑异常
  • 自定义的Item包裹组件未设置宽度100%,灰色背景块没有撑满分配到的列空间,进一步放大了偏移感
可行修复方案

方案1:修正断点列配置(推荐,保留原有响应式逻辑)

把各断点的列宽改为整数匹配值,补全Item组件的宽度和居中属性,修改后代码如下:

<Box 
  sx={{ flexGrow: 1 }} 
  display="flex"
  justifyContent="center"
  alignItems="center" 
  marginLeft={3} 
  marginRight={3} 
  mt={2.5}
>
  <Grid 
    container 
    spacing={{ xs: 1, md: 2, lg:2 }} 
    columns={{ xs: 2, sm: 8, md: 12, lg: 16 }} 
    display="flex"
    justifyContent="center"
    alignItems="center" 
  >
    <Grid item xs={2} sm={4} md={6} lg={7} >
      <Item sx={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
        <Nifty50/>
      </Item>
    </Grid>
    <Grid item xs={2} sm={4} md={6} lg={7}>
      <Item sx={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
        <Sensex/>
      </Item>
    </Grid>
  </Grid>
</Box>

调整说明:

  • sm断点总列数从2改为8,两个图表项各占4列刚好铺满,解决小屏列配置溢出问题
  • md断点两个图表项各占6列,总宽度12完全匹配容器列数,无多余留白
  • lg断点两个图表项各占7列,总宽度14,剩余2列空间会被justifyContent: center自动均分在左右两侧
  • 给Item组件加宽度100%属性,保证灰色背景块完全填满分配到的列空间,不会出现块体本身偏移

方案2:简化为固定等分布局(适配成本更低)

如果不需要复杂的响应式列宽调整,可以直接去掉自定义列数配置,让两个图表永久等宽居中:

<Box 
  sx={{ flexGrow: 1 }} 
  display="flex"
  justifyContent="center"
  alignItems="center" 
  marginLeft={3} 
  marginRight={3} 
  mt={2.5}
>
  <Grid 
    container 
    spacing={2} 
    sx={{ width: '100%' }}
    justifyContent="center"
    alignItems="center" 
  >
    <Grid item xs={6} >
      <Item sx={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
        <Nifty50/>
      </Item>
    </Grid>
    <Grid item xs={6}>
      <Item sx={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
        <Sensex/>
      </Item>
    </Grid>
  </Grid>
</Box>

修改后两个图表永远各占容器一半宽度,左右留白完全对称,不会出现偏移问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 06:09:20