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

React+Material UI+Tailwindcss实现博客卡片等高与子元素对齐

解决卡片高度不一致及子元素对齐问题

要让所有博客卡片高度统一且内部元素对齐,只需对现有代码做几处关键修改,核心思路是让卡片及内部容器撑满网格项高度,并通过Flex布局控制子元素的空间分配:

修改步骤

  • 让卡片占满网格项高度:给<Card>和<CardActionArea>添加h-full类,确保它们完全填充所在Grid item的高度。
  • 设置内部Flex容器撑满高度:给包裹卡片内容的<div>添加h-full,配合原本的flex-col,让子元素垂直排列并占满整个卡片空间。
  • 让内容区域自动填充剩余空间:给<CardContent>添加flex-1,这样无论文章描述长短,都会自动填充CardHeader、CardMedia与CardActions之间的剩余空间,确保底部的CardActions始终对齐。

修改后的完整代码

function Posts({ posts }) {
  return (
    <div className="mt-10">
      <Container maxWidth="lg">
        <Grid
          container
          rowSpacing={8}
          columnSpacing={8}
          direction="row"
          justifyContent="center"
        >
          {posts.map((post, index) => (
            <Grid key={index} item xs={12} sm={12} md={6} lg={4}>
              <Card className="h-full">
                <CardActionArea className="h-full">
                  <div className="flex flex-col h-full">
                    <CardHeader
                      avatar={
                        <Avatar>{post?.username?.substring(0, 1)}</Avatar>
                      }
                      title={post?.username}
                      subheader="date"
                      subheaderTypographyProps={{
                        color: "primary.dark",
                      }}
                      color="primary.main"
                    />
                    <CardMedia
                      component="img"
                      height="194"
                      image={post?.photoURL}
                    />
                    <CardContent className="flex-1">
                      <Typography variant="h6" color="primary.main">
                        {post.description}
                      </Typography>
                    </CardContent>
                    <Divider variant="middle" className="bg-[#fcfcfc]" />

                    <CardActions>
                      <IconButton>
                        <MdFavorite className="text-red-500" />
                      </IconButton>
                    </CardActions>
                  </div>
                </CardActionArea>
              </Card>
            </Grid>
          ))}
        </Grid>
      </Container>
    </div>
  );
}

export default Posts;

修改完成后,所有卡片会自动适配网格项高度,底部的点赞按钮区域将固定在卡片底部,完全匹配你想要的示例效果。

内容的提问来源于stack exchange,提问作者M7md-Dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:54:19