object-fit & object-position
object-fit controls how a replaced element's content — an img or video — is resized to fill its box, when the content's natural aspect ratio doesn't match the box's. Without it, an image forced into a box of a different shape either distorts (stretches unevenly) or overflows. object-fit gives you the same "resize mode" choices you'd find in a native image viewer — crop to fill, fit without cropping, stretch, or don't resize at all.
The four values
Value | Behavior |
|---|---|
cover | Scales to fill the box completely, cropping any overflow. Aspect ratio preserved, no letterboxing, some content may be cut off. |
contain | Scales to fit entirely within the box without cropping. Aspect ratio preserved, may leave empty space (letterboxing) on one axis. |
fill | Stretches to exactly fill the box, ignoring aspect ratio. No cropping, but the content can look squashed or stretched. |
none | Ignores the box size entirely — renders at the content's natural size, which may overflow or underflow the box. |
Worked example — a fixed-ratio image gallery
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 8px;
}
.gallery img {
width: 100%;
aspect-ratio: 1 / 1; /* every tile is a perfect square box */
object-fit: cover; /* crop each photo to fill that square,
regardless of its original dimensions */
border-radius: 4px;
}Without object-fit: cover, a mix of portrait and landscape photos forced into identical square boxes would either distort or leave gaps. With it, every tile is a clean, uniformly-sized square, each showing a sensibly cropped version of its source photo.
object-position — choosing the focal point
When object-fit crops content (typically with cover), some of the image is cut off. object-position controls WHICH part stays visible — the crop's focal point — using the same keyword/percentage syntax as background-position.
/* Default focal point is the center */
.avatar {
width: 96px;
height: 96px;
object-fit: cover;
object-position: center; /* default */
}
/* Bias the crop toward the top — useful for portraits
where the interesting part (the face) is near the top */
.portrait-thumb {
object-fit: cover;
object-position: top center;
}
/* Precise focal point using percentages */
.hero-photo {
object-fit: cover;
object-position: 30% 20%;
}