Write aspect-ratio and object-fit and see the box the browser measures: the cropped part of the photo, the empty room, the ignored ratio. An interactive…
Why it matters
Before 2021, a responsive 16:9 video needed the "padding-top hack". Now it is one line. Add object-fit, and a photo of any ratio fits a box of any ratio without squashing.
The key idea
aspect-ratio works out the auto side, object-fit places the content
Common mistakes
Setting aspect-ratio + an explicit height ignores the ratio The ratio only works out an auto side. Write just one, usually width (or width: 100%) + aspect-ratio.
object-fit on a div does nothing at allobject-fit is only for replaced elements: img, video, canvas. For a div with a background image, use background-size: cover/contain.
Still unsure about aspect-ratio because of old browsers Chrome, Edge, Firefox and Safari 15+ have supported it since 2021. The padding-top hack fallback is only needed if your audience is still on browsers older than that.
An aspect-ratio: 1 card grows because of long words The ratio is preferred, not forced: with visible overflow the box may not be shorter than its content. overflow: auto or min-height: 0 lets the ratio win.
Try it in this playground
Set aspect-ratio to 1, then drag the easel width The frame stays square at any width: its height comes from its width.
Try object-fit cover, then contain cover: full, the rest faint outside the frame. contain: whole, the rest of the frame hatched.
Write height: 200px in the other field The ratio is ignored: width and height are both fixed.
Switch the element to a divobject-fit stops applying: a div is not a replaced element.