object-fit & aspect-ratio

Images and videos rarely have exactly the proportions your layout needs. object-fit controls how media fills its box — cropping or letterboxing instead of stretching — and aspect-ratio gives any element consistent proportions, which also prevents layout shift.

The stretching problem

Try it yourself
Result

A portrait photo forced into a landscape box is distorted.

object-fit

Try it yourself
Result
ValueBehaviour
fillStretch to fill (default — distorts)
coverFill the box, cropping the overflow — for thumbnails and heroes
containFit entirely inside, leaving empty space — for logos and product shots
noneOriginal size, cropped
scale-downLike contain, but never enlarges

object-position

Try it yourself
Result

When cover crops an image, object-position chooses which part stays visible — top keeps faces in portrait photos.

aspect-ratio

Try it yourself
Result

aspect-ratio sets a preferred width-to-height ratio. Give the element a width (or let the layout decide), and the height follows. It replaces the old "padding-top: 56.25%" hack for responsive video boxes.

Consistent card images

Try it yourself
Result

Combining aspect-ratio with object-fit: cover gives every card image the same shape, whatever proportions the uploaded photos have — essential for user-generated content.

aspect-ratio and layout shift

When an <img> has width and height attributes, browsers automatically compute an aspect ratio from them, reserving space before the image loads. That's why setting those attributes matters even when CSS controls the final size. For other elements — embeds, ads, skeleton placeholders — set aspect-ratio in CSS to reserve the space.

Minimum sizes still win

Try it yourself
Result

By default, content can make an aspect-ratio box taller. Add min-height: 0 and overflow: auto if the ratio must be strict.

Try it yourself

Try it yourself
Result