CSS aspect-ratio

The aspect-ratio property in CSS allows you to control the ratio between the width and the height of an element. This property is particularly useful for maintaining consistent aspect ratios for elements such as videos, images, or containers without needing to rely on padding hacks or JavaScript.


Syntax of aspect-ratio

</>
Copy
aspect-ratio: number/number | initial | inherit;

Values

ValueDescription
number/numberSpecifies the width-to-height ratio. For example, 16/9 means the width is 16 units, and the height is 9 units.
initialSets the property to its default value (undefined aspect ratio).
inheritInherits the value from the parent element.

Default Value

Undefined (no aspect ratio is applied by default).


Examples for aspect-ratio

Using the CSS aspect-ratio Property

The following examples demonstrate how the aspect-ratio property can be used to maintain specific aspect ratios for elements like containers or images.

</>
Copy
/* Set a 16:9 aspect ratio */
.element {
  aspect-ratio: 16/9;
}

/* Set a 1:1 aspect ratio for a square */
.element {
  aspect-ratio: 1/1;
}

/* Inherit the aspect ratio from the parent */
.element {
  aspect-ratio: inherit;
}

Example for Applying aspect-ratio to Containers

The following example demonstrates how to use the aspect-ratio property to create responsive containers with consistent aspect ratios.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<style>
  .container {
    background-color: lightblue;
    margin: 10px;
    border: 2px solid #000;
  }

  .aspect-16-9 {
    aspect-ratio: 16/9;
    width: 300px;
  }

  .aspect-1-1 {
    aspect-ratio: 1/1;
    width: 200px;
  }
</style>
</head>
<body>

<h1>CSS aspect-ratio Example</h1>

<div class="container aspect-16-9">16:9 Container</div>
<div class="container aspect-1-1">1:1 Container</div>

</body>
</html>

For .aspect-16-9, the aspect ratio is set to 16/9, making the container maintain a width that is 16 units for every 9 units of height. With a width of 300px, the height is calculated as 168.75px.

For .aspect-1-1, the aspect ratio is set to 1/1, resulting in a perfect square container. With a width of 200px, the height is also 200px.

The aspect ratio ensures that the dimensions of the elements scale proportionally, regardless of the container size or content.


Browser Support

The aspect-ratio property is supported in modern browsers. Below is a compatibility table:

BrowserVersion
Chrome88
Edge88
Firefox89
Safari15
Opera74