aspect-ratio

Lock an element to a shape — 16:9, 1:1, 4:3 — and kill layout-shift on media without padding hacks.

Remember the padding-bottom: 56.25% trick for responsive video embeds? You can forget it. The aspect-ratio property does the job in one honest line:

.video { aspect-ratio: 16 / 9; }
.avatar { aspect-ratio: 1; }   /* a perfect square */

Give an element a width and aspect-ratio computes the height for you (or vice versa). As the width flexes, the height follows and the shape holds.

Why this matters beyond convenience

It's a real performance and UX win. Reserving the correct box before an image or video loads eliminates layout shift — that jarring jump when media pops in and shoves everything down. That directly improves your Cumulative Layout Shift score.

Pair it with object-fit

For images, combine aspect-ratio with object-fit: cover so the picture fills the locked box and crops gracefully instead of stretching.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A developer sets aspect-ratio: 16 / 9 on a video embed container so it maintains the correct proportions at any width without the old padding-top hack.
  • A designer uses aspect-ratio: 1 to ensure profile avatar squares stay perfectly square regardless of the image's natural dimensions.
  • A developer uses aspect-ratio with object-fit: cover on product listing images so all thumbnails are a uniform rectangle, preventing layout shift.

More examples

Responsive 16/9 video embed

Replaces the old percentage padding-top hack with aspect-ratio: 16/9 for a simpler responsive video embed container.

Example · css
.video-wrapper {
  width: 100%;
  aspect-ratio: 16 / 9;
}

.video-wrapper iframe {
  width: 100%;
  height: 100%;
  border: none;
}

Square avatar with aspect-ratio

Locks the avatar to a 1:1 ratio so it is always a perfect square (and circle) regardless of the source image's shape.

Example · css
.avatar {
  width: 48px;
  aspect-ratio: 1;
  border-radius: 50%;
  object-fit: cover;
}

Uniform product card thumbnails

Forces all product images to a 4:3 aspect ratio with cover cropping, preventing layout shift from variable image sizes.

Example · css
.product-img {
  width: 100%;
  aspect-ratio: 4 / 3;
  object-fit: cover;
  object-position: center;
  display: block;
}

Discussion

  • Be the first to comment on this lesson.
aspect-ratio — CSS | SoundsCode