Codectionary / Developer documentation / CSS

aspect-ratio

aspect-ratio sets a preferred width-to-height ratio for an element, letting the browser automatically calculate one dimension from the other. This replaced older, hackier techniques (like the "padding-top trick") for maintaining consistent proportions on responsive elements like video embeds and images.

Syntax

aspect-ratio: width / height;

Examples

A Responsive Video Embed

The classic use case - maintaining a 16:9 ratio at any width.

.video-embed {
  width: 100%;
  aspect-ratio: 16 / 9; /* height is calculated automatically to maintain the ratio */
}

.video-embed iframe {
  width: 100%;
  height: 100%;
}

Square Thumbnails and Image Placeholders

Reserving consistent space before an image loads, preventing layout shift.

.thumbnail {
  width: 100%;
  aspect-ratio: 1 / 1; /* always a perfect square */
  object-fit: cover;
}

Parameters and values

  • aspect-ratio (width / height | auto): Sets a preferred proportional relationship between width and height

Best practices

  • Use aspect-ratio instead of the old "padding-top percentage" hack for maintaining proportions - it is far more readable and intuitive
  • Combine aspect-ratio with object-fit: cover on images/videos so content fills the box correctly without distortion
  • Reserve consistent aspect-ratio space for images before they load, to prevent content from jumping around during page load (improves Cumulative Layout Shift)
  • Remember explicit width/height attributes on <img>/<video> elements still matter for aspect-ratio to work correctly without JavaScript

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation