CSS Aspect Ratio Boxes

Maintain consistent aspect ratios for media containers using CSS aspect-ratio property without padding hacks.

CssData Fetching

Code

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

.square {
  aspect-ratio: 1;
}

.portrait {
  aspect-ratio: 3 / 4;
}

CSS Aspect Ratio Boxes

Maintain consistent aspect ratios for media containers using CSS aspect-ratio property without padding hacks.

Code

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

.square {
  aspect-ratio: 1;
}

.portrait {
  aspect-ratio: 3 / 4;
}

Explanation

Each box keeps its ratio as the width flexes: a 16 / 9 video, a 1 square, and a 3 / 4 portrait. Expected behavior: the height is derived from the width, so the element no longer needs a padding-top percentage hack. Limitation: an explicit height or a replaced element’s own intrinsic size can override the declared ratio.

Interactive Tools for This Topic