2 min read

CSS Aspect Ratio

The aspect-ratio property allows you to define the preferred aspect ratio for an element (width-to-height ratio). This is extremely useful for preventing layout shifts (CLS) when loading images or videos, and for creating responsive components that maintain their shape.

1. Syntax

aspect-ratio: <ratio>;
  • <ratio>: A width/height ratio (e.g., 16 / 9, 1 / 1).
  • auto: The default. The element uses its intrinsic aspect ratio (if it has one).

2. Basic Usage

.box {
  width: 100%;
  aspect-ratio: 16 / 9;
  background-color: lightblue;
}

In this example, the height will automatically be calculated based on the width to maintain a 16:9 ratio. If the width is 1600px, the height will be 900px.

3. Preventing Layout Shifts

Images and videos often cause layout shifts because the browser doesn't know their height until they load. By setting aspect-ratio, the browser reserves the correct amount of space immediately.

img {
  width: 100%;
  height: auto;
  aspect-ratio: 4 / 3;
}

4. Interaction with Dimensions

  • If both width and height are set, aspect-ratio is ignored.
  • If only one dimension is set (e.g., width), aspect-ratio determines the other (height).
  • It works well with min-height or max-width.
.card {
  width: 300px;
  aspect-ratio: 1 / 1; /* Creates a square */
}

5. The "Padding Hack" (Legacy)

Before aspect-ratio, developers used the "padding-top hack" to maintain ratios.

/* Old way */
.container {
  width: 100%;
  padding-top: 56.25%; /* 16:9 ratio (9/16 * 100) */
  position: relative;
}
.content {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
}

The aspect-ratio property replaces this complex boilerplate with a single line.

programming/css/css programming/css/box-model programming/css/object-fit