CSS Proportional Dimensions with Aspect-Ratio
aspect-ratio
is a CSS property that lets boxes maintain proportional dimensions. This means the height and width are calculated as a ratio. The aspect ratio argument accepts two numbers, as is the case when defining the proportion of all aspect ratios.
Simply put, the aspect-ratio
property helps us to size elements consistency so that the ratio stays the same at any screen resolution. This is particularly useful when trying not to crop images, or keeping consistency.
Traditionally, an old hack would be used when trying to implement an aspect ratio using ‘height: 0px; padding-top: 66%;
‘ which is an ugly solution. To replace this, the CSS Box Sizing Module Level 4 specification added documentation for an aspect-ratio property that browsers such as chrome and safari quickly adopted as of 2021. The aspect-ratio
property is gaining wide support, but its worth noting that it won’t work on older browsers pre-2021.’
The aspect ratio property can easily be implemented as shown below, and can be implemented on any tag in the HTML specification – most frequently it’s likely to be used with the img
tag which has the highest demand for maintaining a ratio. It’s also worth noting that it doesn’t apply to inline elements, so make sure you are setting to block or flex for optimal usage.
/* Aspect Ratio Syntax */
aspect-ratio: width / height;
/* Triple width */
img {
aspect-ratio: 3 / 1;
}
/* PC Monitor aspect-ratio */
img {
aspect-ratio: 16 / 9;
}
Using Width & Height with aspect-ratio.
It’s also worth noting that a width
or a height
doesn’t need to be directly set. By setting the aspect ratio without a width element, width: auto will be used by default to set the elements dimensions. However a width can be set, and it will follow the width set, and adjust the height to correspond to the aspect-ratio
. Furthermore, if both a height and width are set on an element, the aspect-ratio property will be completely ignored.
Even better, the min-height
property can be used to allow the overflow of content. Cool huh? min-height: 0;
can be used to preserve the aspect-ratio and stop content from spilling out of an aspect-ratio element.
Useful Examples
Its that time to show some useful examples, or at-least how I use the aspect-ratio
css property, which is most commonly on the img
and iframe
elements.
/* Image Example */
img {
display: block;
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
}