The aspect-ratio
CSS property lets you set an element's width-to-height ratio. When the parent container or viewport changes size, the browser automatically adjusts the element's dimensions to maintain this ratio. The aspect ratio helps calculate automatic sizes and influences other layout calculations.
At least one of the box's sizes needs to be automatic in order for aspect-ratio
to have any effect. If neither the width nor height is an automatic size, then the provided aspect ratio has no effect on the box's preferred sizes.
Syntax
.element {
aspect-ratio: 2 / 1; /* ↔️ x is double of the y ↕️ */
}
.element {
aspect-ratio: 1 / 1; /* ⏹ a perfect square */
}
/* fallback to 'auto' for replaced elements */
.element {
aspect-ratio: auto 3/4;
}
.element {
aspect-ratio: 9/6 auto;
}
The box's preferred aspect ratio is the specified ratio of
width
/ height
. If height and the preceding slash character are omitted,
height
defaults to 1
. Size calculations involving preferred aspect ratio work with the dimensions of the box specified by box-sizing
.For aspect-ratio
to work, either the width or height must be set to "auto". The aspect ratio won't affect an element's preferred sizes if both width and height are fixed.
The property accepts either the keyword auto
, a <ratio>
, or both. For replaced elements like </img>
, when both values are specified, the given ratio applies temporarily until the content loads. Once loaded, the auto
value takes effect, using the content's intrinsic aspect ratio.
For non-replaced elements, the specified ratio
is always used. It applies to all elements except inline boxes and internal ruby or table boxes.
Practical example
In this example, the width of the <div>
elements has been set to 150px
and height to auto
. Since the width value is fixed here, the aspect-ratio
property affects only the height of the <div>
elements to maintain the specified width-to-height ratio.
.box div:nth-child(n) {
width: 150px;
height: auto;
background-color: hsl(189, 75%, 74%);
border: solid 2px hsl(0, 1%, 66%);
border-radius: 3px;
}
.box div:nth-child(1) {
/* width: 150px and height: 150px */
aspect-ratio: 1/1;
}
.box div:nth-child(2) {
/* width: 75px and height: 150px */
/* Because height default to 1 */
aspect-ratio: 0.5;
}
.box div:nth-child(3) {
/* width: 150px and height: 150px */
/* Because height default to 1 */
aspect-ratio: 1;
}
.box div:nth-child(4) {
/* width: 150px and height: 75px */
aspect-ratio: 1/0.5;
}
The display below will correspond to the CSS code above, if you want to see the full code source, click on Open Sandbox in the code demo box.
You can find out more here:
Official Mozilla doc
🔍. Similar posts
Simplifying Layouts With React Fragments
18 Jan 2025
Stop Installing Node Modules on Your Docker Host - Install Them in the Container Instead
14 Jan 2025
An Easy to Understand React Component Introduction for Beginners
14 Jan 2025