Aspect Ratio in CSS
The aspect-ratio CSS property enables you to specify the preferred width-to-height ratio for an element’s box. When you resize the element, the browser will automatically adjust the element to maintain the specified aspect ratio.
Here is aspect-ratio in action:
See the Pen Aspect Ratio in CSS: Snippet 1 by Kyle Ross (@kylejamesross) on CodePen.
Equivalent CSS:
img {
width: 100px;
height: 400px;
}
Syntax
aspect-ratio: auto || <ratio>
| Property | Value |
|---|---|
| Initial value | auto |
| Applies to | all elements except inline boxes and internal ruby or table boxes |
| Inherited | no |
| Percentages | n/a |
| Computed value | specified keyword or a pair of numbers |
| Animation type | discrete |
Examples
aspect-ratio: auto; /* default - no aspect ratio sizes normally */
aspect-ratio: 1 / 1; /* width / height */
aspect-ratio: 1 / 3; /* width / height */
aspect-ratio: auto 1 / 3; /* Use instrinsic ratio otherwise 1 / 3 */
Fallback to natural aspect ratio
When using both auto and <ratio>, the element’s intrinsic aspect ratio takes precedence. See it in action:
See the Pen Aspect Ratio in CSS: Snippet 2 by Kyle Ross (@kylejamesross) on CodePen.
No width or height is defined
If neither width nor height is specified, it defaults to using auto for the width:
See the Pen Aspect Ratio in CSS: Snippet 3 by Kyle Ross (@kylejamesross) on CodePen.