What is aspect-ratio?

The aspect-ratio property gives an element a preferred width-to-height ratio, such as 16 / 9 or 1, so when only one dimension is set the browser calculates the other. It replaced the old "padding-top: 56.25%" hack for responsive videos and cards, and it helps prevent layout shift.

Usage

.video { width: 100%; aspect-ratio: 16 / 9; }
.avatar { width: 48px; aspect-ratio: 1; border-radius: 50%; }
.card-img { width: 100%; aspect-ratio: 4 / 3; object-fit: cover; }

How it behaves

  • It only applies when at least one dimension is auto; if both width and height are set, the ratio is ignored.
  • It is a preferred ratio: content larger than the box can still stretch it, unless you add min-height: 0 or overflow: hidden.
  • aspect-ratio: auto 16 / 9 uses the content's natural ratio when known (e.g. a loaded image) and 16/9 before that.

Images and CLS

Browsers automatically derive aspect-ratio from an <img>'s width and height attributes (aspect-ratio: attr(width) / attr(height) in their default stylesheet). That is why setting those attributes reserves the right space before the image loads, even with width: 100%; height: auto.

Common uses

  • Responsive iframes for YouTube or maps.
  • Uniform card and gallery thumbnails.
  • Square grid cells (aspect-ratio: 1).
  • Skeleton placeholders that match the final content's shape.

Interview tip

Mention its link to Cumulative Layout Shift; it shows performance awareness.

Code example

html
1<style>
2 body { font-family: system-ui; max-width: 520px; }
3 .video { width: 100%; aspect-ratio: 16 / 9; border: 0; border-radius: 8px; background: #0b1020; }
4 .grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin: 12px 0; }
5 .grid div { aspect-ratio: 1; background: #2b4bff; border-radius: 6px; }
6 .card img { width: 100%; height: auto; aspect-ratio: 4 / 3; object-fit: cover; border-radius: 8px; display: block; }
7 .skeleton { width: 100%; aspect-ratio: 4 / 3; border-radius: 8px; background: linear-gradient(90deg, #e5e7eb, #f8fafc, #e5e7eb); }
8</style>
9<iframe class="video" src="https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ" title="Embedded video" loading="lazy" allowfullscreen></iframe>
10<div class="grid"><div></div><div></div><div></div><div></div></div>
11<div class="card"><img src="https://picsum.photos/id/1040/800/450" alt="Castle on a hill" width="800" height="450"></div>
12<p>Skeleton with the same shape reserves space before content loads:</p>
13<div class="skeleton"></div>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.

Open in study app