Home > front end >  Why does object-fit impact my image quality and how to avoid it
Why does object-fit impact my image quality and how to avoid it

Time:01-24

Using object-fit: cover has a bad impact on my image quality.

We can see that when the element uses object-fit: cover the hair in the image gets pixelated.

enter image description here

Here's a demo of my code: https://codepen.io/widness/pen/NWBywgy

I don't understand why the quality is worse and how to avoid this effect.

Additional

  • The problem isn't the image quality itself -> here is the image
  • The loss of the image quality is quite subtle, focusing on the light part of the hair makes it more visible

CodePudding user response:

It looks like that's just how the browser handles downscaling: object-fit : cover gives pixelated images on chrome. Whenever I stumble upon a sharpness issue the first I always try is a translate3d and it solves it most of the time. In your case I'm not sure it fixes it 100% but it does look better.

If you can, try to use a picture that has a width and height closer to it's final rendering size, those always render better (seen in second example - scroll down to see it)

.example-container {
  display: flex;
  width: 100%;
}

.object-fit,
.object-notFit {
  display: flex;
  flex-direction: column;
  height: 220px;
  width: 180px;
}
picture {
  height: 100%;
  width: 100%;
}
 .object-fit img {
  object-fit: cover !important;
  transform: translate3d(0, 0, 1px);
  height: 100% !important;
  width: 100%;
}
<div >
<div >
<picture >
  <img alt="image"  src="https://thumbs.dreamstime.com/b/teen-girl-makes-grimace-consternation-20146520.jpg" style="
    object-fit: initial;
    height: unset;
">
</picture>
  object not fit
  </div>

<div >
<picture>
  <img alt="image"  src="https://thumbs.dreamstime.com/b/teen-girl-makes-grimace-consternation-20146520.jpg" style="
    object-fit: initial;
    height: unset;
">
  
</picture>
  object fit
</div></div>

<h1>Downscaled</h1>
<div >
<div >
<picture >
  <img alt="image"  src="https://i.postimg.cc/nVKnTMFJ/rsz-imageimage.jpg" style="
    object-fit: initial;
    height: unset;
">
</picture>
  object not fit
  </div>

<div >
<picture>
  <img alt="image"  src="https://i.postimg.cc/nVKnTMFJ/rsz-imageimage.jpg" style="
    object-fit: initial;
    height: unset;
">
  
</picture>
  object fit
</div></div>

There's also an image-rendering property but it doesn't seem to help here: https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering?retiredLocale=de

PS: I think the extremely smooth image on the left is partly an error. The browser introduces a tiny little bit of blurring while downscaling. If you look at the full scale image in another tab you notice that even that isn't as smooth as the thumbnail on the left.

  • Related