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

React中如何居中Material UI Card组件?

React中Material UI Card组件居中解决方案

你的代码存在两个核心问题导致Card无法正常居中:

  • Card的display、alignItems、justifyContent属性未放在sx配置对象内,Material UI仅识别sx中的样式规则。
  • Grid容器缺少必要的空间占满与垂直居中配置(若需垂直居中)。

以下是修正后的完整代码:

<Grid container 
  sx={{ 
    minHeight: '100vh', // 让Grid占满视口高度,实现垂直居中
    justifyContent: 'center', 
    alignItems: 'center' 
  }}
>
  <Card sx={{ 
    maxWidth: 345,
    display: 'flex',
    flexDirection: 'column', // 显式声明垂直排列,确保内部元素排版正常
    alignItems: 'center',
    justifyContent: 'center'
  }}>
    <CardMedia
      component="img"
      height="140"
      image="astroline-white_betterq.png"
      alt="astroline banner"
    />
    <CardContent>
      <Typography gutterBottom variant="h5" component="div">
      </Typography>
      <Typography variant="body2" color="text.secondary">
        Astroline is a space / scifi game about a apocalyptic disaster that happened on Earth.
      </Typography>
    </CardContent>
    <CardActions>
      <Button size="small" elevation="1" onClick={() => navigate("/astroline")}>
        Learn More
      </Button>
    </CardActions>
  </Card>
</Grid>

关键修正说明:

  1. 将Card的所有布局样式移入sx对象,确保Material UI能正确解析应用。
  2. 给Grid容器添加minHeight: '100vh'和alignItems: 'center',实现Card在视口中水平+垂直居中;若仅需水平居中,可删除minHeight与alignItems配置。
  3. 给Card添加flexDirection: 'column',保证内部CardMedia、CardContent等元素垂直有序排列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:36:20