The short answer

#

Use the aspect-ratio property. Give the element a width (or let it fill its container) and the browser works out the height from the ratio. It has been supported in all major browsers since 2021, so the old padding-top hack is no longer needed.


_10
.video {
_10
width: 100%;
_10
aspect-ratio: 16 / 9;
_10
}

Why it happens

#

By default, a block element's height comes from its content. A div meant to hold a video, a map or a placeholder image has no content when the page first renders, so it collapses to zero height, then jumps when the content arrives. Even with content, there was no direct way to say "keep this box twice as wide as it is tall".

The old workaround used the fact that percentage padding is calculated from the width: padding-top: 56.25% gave a 16 by 9 box. It worked, but it needed an extra wrapper and absolutely positioned children.

aspect-ratio sets a preferred ratio directly. When one dimension is known and the other is auto, the browser calculates the missing one from the ratio.

How to fix it

#

Set a ratio on the box

The value is width divided by height, written with a slash. A single number also works, so aspect-ratio: 1 gives a square.


_10
.avatar {
_10
width: 4rem;
_10
aspect-ratio: 1;
_10
border-radius: 50%;
_10
}
_10
_10
.card-media {
_10
aspect-ratio: 4 / 3;
_10
}

Crop images and videos to fit

When media does not match the box's ratio, it stretches. Add object-fit to crop it instead, and object-position to choose which part stays visible.


_10
.thumbnail {
_10
width: 100%;
_10
aspect-ratio: 16 / 9;
_10
object-fit: cover;
_10
object-position: center;
_10
}

Size embeds such as iframes

Video embeds often arrive with fixed width and height attributes. Override the height with auto so the ratio can take over.


_10
iframe {
_10
width: 100%;
_10
height: auto;
_10
aspect-ratio: 16 / 9;
_10
}

Stop content from stretching the box

aspect-ratio is a preferred size, not a hard rule. Because a block's min-height defaults to auto, content taller than the ratio allows will make the box grow. If you would rather clip or scroll the content, add an overflow value, which lets the ratio win.


_10
.tile {
_10
aspect-ratio: 1;
_10
overflow: auto;
_10
}

Common pitfalls

#
  • Setting both width and height. When both are fixed, there is nothing left to calculate and aspect-ratio is ignored.
  • Wondering why text makes the box taller. That is the automatic minimum height at work; add overflow or min-height: 0 if the ratio must hold.
  • Forgetting width and height attributes on img tags. Browsers use them to reserve the right ratio before the image loads, which prevents layout shift, even when CSS sets height: auto.
  • Stretching media without object-fit. The box keeps its ratio, but the picture inside gets squashed.
#
file under:
CSS

quick question

Was this resource helpful?