Keeping Elements in Proportion With CSS aspect-ratio

CSS finally has a direct way to say that an element should stay square, widescreen, or any other proportion. The aspect-ratio property replaces a surprising number of padding hacks with one readable declaration.

An aspect ratio is the relationship between width and height. 16 / 9 means the width is 16 units for every 9 units of height; 1 means a square.

.video {
  aspect-ratio: 16 / 9;
}

The browser can calculate the missing dimension when the other one is known. If both width and height are fixed, those sizes win and the ratio has nothing left to calculate.

Images need one more decision

Setting a ratio on an image can give every thumbnail the same shape:

img {
  width: 100%;
  aspect-ratio: 16 / 9;
  object-fit: cover;
}

object-fit: cover fills the box and crops anything that does not fit. It does not ensure that the entire image remains visible. Use contain if seeing all of the image matters more than filling the box.

For an image with intrinsic dimensions, auto lets the browser use its natural ratio. You can also provide a fallback ratio while the image loads:

img {
  aspect-ratio: 4 / 3;
}

A square without matching dimensions

Only one dimension is needed:

.avatar {
  width: 3rem;
  aspect-ratio: 1;
  object-fit: cover;
  border-radius: 50%;
}

This is one of those CSS properties that is useful precisely because it is boring. State the proportion, let layout calculate the other side, and keep object-fit separate for replaced content such as images and videos.