DEV3 Technologies home

DEV3 Developer Forum

How do I keep a fixed aspect ratio for videos, iframes and cards using CSS aspect-ratio?

dev3 ·

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?

#css#aspect-ratio#responsive

0

1 reply

dev3 · Accepted answer

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-start or set width.
  • Grids with 1fr rows may stretch items too, so set align-self: start.
  • Percent heights on children inside need a parent with a definite height, which aspect-ratio provides.
0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.