CSS aspect-ratio Property
More "Try it Yourself" examples below.
Definition and Usage
The aspect-ratio
property allows you to define the ratio between width and height of an element.
If aspect-ratio
and width
properties are set, the height will follow in the defined aspect ratio.
To better understand the aspect-ratio
property,
view a demo.
Tip: Use the aspect-ratio
property in responsive layouts where elements often vary in size and you want to preserve the ratio between width and height.
Default value: | auto |
---|---|
Inherited: | no |
Animatable: | yes. Read about animatable Try it |
Version: | CSS3 |
JavaScript syntax: | object.style.aspectRatio="16/9" Try it |
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
Property | |||||
---|---|---|---|---|---|
aspect-ratio | 88 | 88 | 89 | 15 | 74 |
CSS Syntax
aspect-ratio: number/number|initial|inherit;
Property Values
Property Value | Description | Demo |
---|---|---|
number | First number specifies the number for width in aspect ratio. | Demo ❯ |
number | Second number specifies the number for height in aspect ratio. Optional. If not set, number for height is 1 as default. | Demo ❯ |
initial | Sets this property to its default value. Read about initial | |
inherit | Inherits this property from its parent element. Read about inherit |
More Examples
Example
The aspect-ratio
property is good for controlling aspect ratio of div elements if the div elements are supposed to vary in size. This can be the case in an image gallery when you want div elements to be flexible in size to look good on all devices, but you also want ratio between width and height of the images to be preserved:
#container > div {
aspect-ratio: 3/2;
}
Related Pages
CSS tutorial: CSS Grid Layout Module
CSS object-fit property: CSS Object-fit property
CSS object-position property: CSS Object-position property