aspect-ratio
finally has good browser support, being supported in all major browsers bar IE.
aspect-ratio: 16 / 9;
Although the property accepts a single number (e.g. 0.66), two numbers should always be passed to represent a fraction and deal with rounding issues. 0.66
!= 2/3
The aspect ratio is only preferred, and is calculated using either the width or the height, whichever is set. If neither is set, it falls back to the default width: auto
present on all elements. That means an element with an aspect ratio of 1 / 1
and a height of 300px
will be given a width of 300px
.
If both width and height are explicitly set (e.g. with pixels), the aspect ratio is ignored.
The aspect ratio is considered 'preferred', as extra content will break the aspect ratio of the element. If this isn't wanted, a minimum width/height can be used to enforce the aspect ratio. Additionally, a fallback can be used.
The following snippet allows you can still set the aspect ratio of the box of the image, with the image keeping its regular dimensions inside of it.
img { width: 100%; height: 100%; object-fit: contain; aspect-ratio: 16 / 9 }
Aspect ratio is also a great way to reserve space on a page for an image before it's loaded. [[20250528114703-image-layout-shift-aspect-ratio]]