How to prevent image with srcset to go beyond intrinsic width?

Viewed 339

Here is the minimal reproducible example:

body {
  margin: 0;
}

div {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  height: 100%; /* has to be 100%, no px or em heights */
}

div img {
  max-height: 100%;
  max-width: 100%;
  object-fit: contain;
}
<div>
  <img src="https://dummyimage.com/300x225/000/fff" srcset="https://dummyimage.com/300x225/000/fff 600w, https://dummyimage.com/768x568/000/fff 768w">
</div>

The problem I have is that the image stretches beyond it's natural dimensions and I need to prevent that.

The aim is to:

  • Parent element of the image in full width and height
  • Image can't be as background-image (SEO)
  • Image can't have fixed width and height

Looking only for CSS solutions.

0 Answers
Related