Avatars that never squash
CaveatThe default is fill, which is why the left face is squashed: a wide photo forced into a square stretches. cover crops instead — but it crops from the centre, so a face near the edge of the photo needs object-position to stay in frame. And the box must have both dimensions: with only a width the height follows the image and there is nothing to crop against.
FallbackWhere it is unsupported you get the stretched version on the left — ugly, but present and labelled. Never fake cover with background-image on a div: that throws away the alt text.
.avatar {
width: 64px;
/* both, or there is nothing to crop */
height: 64px;
object-fit: cover;
/* when the face is not centred */
object-position: 50% 20%;
}
Published
Questions
Why is object-fit: cover not doing anything to my image?
Usually the box has only one fixed dimension, so the other follows the image's own ratio and there is nothing to crop against. Give it both a width and a height. It also has to sit on the <img> or <video> itself, since it does nothing on a wrapper <div>.
How do I stop object-fit: cover from cutting off faces?
Move the crop with object-position. Cover crops around the centre by default, so a head near the top of a portrait loses its forehead; object-position: 50% 20% keeps more of the upper part in frame.
Should avatars use object-fit or background-size: cover?
Use object-fit on a real <img>. A background image on a <div> crops the same way but has no alt text, so screen readers get nothing and the picture disappears when styles fail to load.