aspect-ratio

Draft

Definition

The aspect-ratio property accepts a value in the form of a ratio, e.g., 16 / 9 for a 16:9 aspect ratio, commonly used for widescreen video. This property calculates the other dimension when one is set, maintaining the ratio.

Usage

For example, let’s consider a responsive container meant to hold a video:

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

In this example, the video-container element will always maintain a 16:9 aspect ratio, regardless of the width of the viewport. When the width of the viewport changes, the height of the video-container will adjust automatically to maintain the aspect ratio.

aspect-ratio is incredibly useful when you need an element to maintain its shape while scaling up or down. Video or image containers are prime examples, but it can also be used in grids, cards, and other design elements.

aspect-ratio has good browser support. It is not supported in Internet Explorer 11. You can track the full browser support here.

Before the aspect-ratio property was introduced, a common technique to maintain aspect ratios involved the use of padding. Here’s how you can achieve the same 16:9 aspect ratio with a fallback for older browsers:

.video-container {
  position: relative;
  width: 100%;
  padding-bottom: 56.25%; /* 100% / (16 / 9) */
  height: 0;
}

.video-content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}