What is object-fit?
object-fit controls how a replaced element's content, such as an <img> or <video>, fills its box when the box's aspect ratio differs from the media's. cover fills the box and crops the excess, contain fits the whole image and leaves empty space, and fill (the default) stretches it out of proportion.
Values
fill(default): stretches to the box's exact size, distorting the image.cover: keeps the aspect ratio, fills the box, crops overflow. The usual choice for thumbnails, avatars, cards and heroes.contain: keeps the aspect ratio, shows the whole image, letterboxes. Good for logos and product shots.none: natural size, cropped by the box.scale-down: the smaller ofnoneandcontain.
object-position
Chooses which part of the image stays visible when cropping: object-position: top keeps faces in portrait photos; object-position: 30% 70% targets a focal point.
Typical pattern
.thumb { width: 100%; aspect-ratio: 4 / 3; object-fit: cover; }
Every card image becomes the same shape regardless of the uploaded photo's size.
Compared with background images
background-size: cover does the same for CSS backgrounds, but <img> with object-fit keeps the image as real content, with alt text, lazy loading, srcset and better LCP discovery.
Interview tip
Mention keeping width and height attributes on the image to prevent layout shift, even when CSS changes the displayed shape.
Code example
1<style>2 body { font-family: system-ui; display: flex; flex-wrap: wrap; gap: 12px; }3 figure { margin: 0; text-align: center; }4 img { width: 140px; height: 140px; border: 2px solid #0b1020; background: #f1f5f9; display: block; }5 .fill { object-fit: fill; }6 .cover { object-fit: cover; }7 .contain { object-fit: contain; }8 .top { object-fit: cover; object-position: top; }9 .avatar { width: 64px; height: 64px; border-radius: 50%; object-fit: cover; }10</style>11<figure><img class="fill" src="https://picsum.photos/id/1025/600/300" alt="Pug in a blanket" width="600" height="300"><figcaption>fill (stretched)</figcaption></figure>12<figure><img class="cover" src="https://picsum.photos/id/1025/600/300" alt="Pug in a blanket" width="600" height="300"><figcaption>cover (cropped)</figcaption></figure>13<figure><img class="contain" src="https://picsum.photos/id/1025/600/300" alt="Pug in a blanket" width="600" height="300"><figcaption>contain (letterboxed)</figcaption></figure>14<figure><img class="top" src="https://picsum.photos/id/1027/300/600" alt="Person standing outdoors" width="300" height="600"><figcaption>cover + position top</figcaption></figure>15<figure><img class="avatar" src="https://picsum.photos/id/1027/300/600" alt="Avatar" width="300" height="600"><figcaption>avatar</figcaption></figure>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.