9

img {
  width: 200px;
  height: 150px;
  object-fit: cover;
}
<img src="https://res.cloudinary.com/wisdo/image/upload/v1589582065/mentored-sessions/New/Kim.jpg" />

Codepen Example

Many other images work fine. In other browsers everything also works as expected.

What can be the problem?

Chrome Version 84.0.4147.89

4

1 回答 1

8

It's because the image itself is saved incorrectly or malformed in someway.

I noticed this when I downloaded the original image to my computer, the preview was showing horizontal despite the image dimensions being in portrait orientation (2208 x 2944).

I opened it in Preview rotated it back to what it should be and saved it. I put it up on imgur to grab a link to use:

img {
  width: 200px;
  height: 150px;
  object-fit: cover;
}
<img src="https://i.imgur.com/8OLakxR.jpg" />

Edit for further explanation based on comments from @dgknca:

As @dgknca pointed out, background-position: cover works because the image in this case is not a replaced element, rather the browser gets the image as presented and uses it as a background image

object-fit works on replaced elements such as video, img, iframe and embed (being the most common).

So, in this particular case, it appears that the meta data or other data associated with the actual image was corrupt/malformed/incorrect. So when Chrome interpreted the actual image data for this replaced element, it was trying to do object-fit: cover - to Chrome the image was horizontal and not vertical, so it was being stretched or rather "fit" incorrectly.

The link to the MDN article about replaced elelemts:

https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element

Here's the imporant part:

In CSS, a replaced element is an element whose representation is outside the scope of CSS; they're external objects whose representation is independent of the CSS formatting model.

Put in simpler terms, they're elements whose contents are not affected by the current document's styles. The position of the replaced element can be affected using CSS, but not the contents of the replaced element itself. Some replaced elements, such as elements, may have stylesheets of their own, but they don't inherit the styles of the parent document.

于 2020-07-21T17:44:30.653 回答