最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make CardMedia Images fit its content in MUI 5 - Stack Overflow

programmeradmin1浏览0评论

I want my images to fully fit the CardMedia. Yet since they are of different heights and widths, some of them get cut like so:

Also upon resizing, some images get cut as well:

This is the code for the CardMedia part:

   <Card
      raised
      sx={{
        maxWidth: 280,
        margin: "0 auto",
        padding: "0.1em",
      }}
    >
      <CardMedia
        component="img"
        height="250"
        image={product.img_urls[0]}
        alt={product.name}
        title={product.name}
        sx={{ padding: "1em 1em 0 1em" }}
      />
      // Other Content
    </Card>

Overall, I want to achieve something like this but with all the cards in the same height and width:

Is there any way I can fix this or do I need to resize each image individually?

I want my images to fully fit the CardMedia. Yet since they are of different heights and widths, some of them get cut like so:

Also upon resizing, some images get cut as well:

This is the code for the CardMedia part:

   <Card
      raised
      sx={{
        maxWidth: 280,
        margin: "0 auto",
        padding: "0.1em",
      }}
    >
      <CardMedia
        component="img"
        height="250"
        image={product.img_urls[0]}
        alt={product.name}
        title={product.name}
        sx={{ padding: "1em 1em 0 1em" }}
      />
      // Other Content
    </Card>

Overall, I want to achieve something like this but with all the cards in the same height and width:

Is there any way I can fix this or do I need to resize each image individually?

Share Improve this question edited May 12, 2022 at 9:08 Nima Zarei asked May 12, 2022 at 8:36 Nima ZareiNima Zarei 1,2283 gold badges16 silver badges51 bronze badges 2
  • Looks like a possible duplicate of stackoverflow.com/a/55272024 – Jack465 Commented May 12, 2022 at 9:11
  • @Jack465I I had already checked that out to no avail. – Nima Zarei Commented May 12, 2022 at 9:21
Add a comment  | 

2 Answers 2

Reset to default 17

You need to make your pictures to fill their layouts, AND keep their aspect ratio. The best way is to set their "object-fit" css property to "contain". Try this:

<Card
  raised
  sx={{
    maxWidth: 280,
    margin: "0 auto",
    padding: "0.1em",
  }}
>
  <CardMedia
    component="img"
    height="250"
    image={imageNetwork}
    alt={"alt"}
    title={"titleasdasdsada"}
    sx={{ padding: "1em 1em 0 1em", objectFit: "contain" }}
  />
  // Other Content
</Card>

Try this

parent-image-element {
 width: 100px;
}

image {
 width: 100%;
 max-height: 100px;
}
发布评论

评论列表(0)

  1. 暂无评论