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

React中使用MUI Grid容器实现卡片居中对称排布

实现方案

React 版 Material UI 完全可以实现容器内卡片均匀排布、整体以页面中线为基准对齐的需求。

你当前代码布局异常的原因很明确:

  • 外层Grid容器只设置了spacing={0},没有配置内容分布、对齐的相关属性,网格项默认靠左排列
  • 你写在Grid子项上的textAlign、justifyContent属性只会控制子项内部内容的对齐,不会调整子项本身在网格容器中的位置

修正后代码

只需要调整Grid容器的对齐属性,统一给子项加上内部居中的弹性布局配置即可,代码如下:

<Container maxWidth={false} disableGutters>
  <Box style={styles.background}>
    <Grid 
      container 
      spacing={3} 
      justifyContent="space-evenly" 
      alignItems="center"
    >
      <Grid item sm={12} lg={3} xs={12} sx={{ display: 'flex', justifyContent: 'center' }}>
        <HowToCard 
          title="" 
          description="Entre le numéro de téléphone de la personne que tu aimes" 
        />
      </Grid>
      <Grid item sm={12} lg={3} xs={12} sx={{ display: 'flex', justifyContent: 'center' }}>
        <HowToCard 
          title="" 
          description="La personne que tu aimes est inscrite sur le site"
        />
      </Grid>
      <Grid item sm={12} lg={3} xs={12} sx={{ display: 'flex', justifyContent: 'center' }}>
        <HowToCard 
          title="" 
          description="Vous serez tous les deux prévenus si vous vous aimez mutuellement !"
        />
      </Grid>
    </Grid>
  </Box>
</Container>

调整说明:

  • 给网格容器加justifyContent="space-evenly"可以让所有网格项在水平方向均匀留白、对称分布,中间卡片自然落在页面中线上
  • 大屏断点下把单个卡片的占比从lg=4调整为lg=3,是为了给卡片之间留出均匀间隙,避免卡片紧贴边缘;小屏断点下卡片仍会自动占满整行垂直排列
  • 子项统一加display: flex+justifyContent: center是为了保证卡片本身在所属网格区域内居中,不会偏移
  • spacing数值可以根据你需要的卡片间距大小自行调整

预期效果参考:
均匀对称排布的卡片示意图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 21:18:24