img element with object-fit: contain leaves extra space on x-axis

I have a image inside a div with the div having width: 100% and img having object-fit: contain to ensure the image gets as wide as it can without stretching. However, this leaves a problem I couldn't get rid of where the image element itself is wider than the actual image. Removing the 100% width from it's parent div would solve it, but it would also make the image smaller as it wouldn't take the full possible width. Any ideas on how to solve this, so the img element width would be the same as the image itself, whilst growing to its maximum size?
No description
2 Replies
cheesedie
cheesedieOP2w ago
also the image max height is set to 75vh, removing this would also solve it but I would like to keep the max height
Kingpin
Kingpin2w ago
object-fit contain will make sure the entire image gets displayed in the container you put it in. If you want it to cover the entire container you can use object-fit cover the image wont be stretched but parts of it might be cut off cuz it's trying to fit the entire image over the entire width and height. https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/object-fit
MDN Web Docs
object-fit - CSS | MDN
The object-fit CSS property sets how the content of a replaced element, such as an <img> or <video>, should be resized to fit its container.

Did you find this page helpful?