I used the old padding-bottom: 56.25% hack for YouTube embeds. Is there a cleaner way, and how do I use it for square avatars and cards?
DEV3 Developer Forum
How do I keep a fixed aspect ratio for videos, iframes and cards using CSS aspect-ratio?
Every post is reviewed first. Usually reviewed within 24 hours.
1 reply
Use the aspect-ratio property
Supported in all current browsers. No wrapper or padding hack.
.video {
width: 100%;
aspect-ratio: 16 / 9;
}
.video iframe { width: 100%; height: 100%; border: 0; }
.avatar { width: 4rem; aspect-ratio: 1; border-radius: 50%; object-fit: cover; }
.card-media { aspect-ratio: 4 / 3; }
Tailwind utilities: aspect-video (16/9), aspect-square, and arbitrary values like aspect-[4/3] or aspect-[21/9].
<div class="aspect-video w-full overflow-hidden rounded-lg">
<iframe class="size-full" src="https://www.youtube.com/embed/ID" title="Product tour" allowfullscreen></iframe>
</div>
How it resolves
The browser computes the missing dimension from the ratio: with a defined width, height is derived (or the opposite). If you set both width and height, the ratio is ignored.
Content bigger than the box
By default aspect-ratio behaves like a preferred ratio: if content overflows (for example a long paragraph in a card) the box grows taller. Add min-height: 0 or overflow: hidden if you need a strict box.
Images
Setting width and height HTML attributes on an img gives the browser a default aspect ratio, which reserves space and avoids layout shift. Combine with object-fit: cover when you force another ratio.
Pitfalls
- A flex item in a column can have its height stretched, ignoring the ratio; use
align-self: flex-startor setwidth. - Grids with
1frrows may stretch items too, so setalign-self: start. - Percent heights on children inside need a parent with a definite height, which
aspect-ratioprovides.