Image Aspect Ratio
Overview
The aspect ratio of an image is the proportional relationship between its width and its height. It is commonly expressed as two numbers separated by a colon, as in 16:9. For example, a 16:9 aspect ratio means that for every 16 pixels of width, there are 9 pixels of height.
When you are working with images on the web, it is important to consider the aspect ratio of the image. If you are using an image in a responsive design, you will want to make sure that the image scales properly as the viewport changes size. If the aspect ratio of the image is not preserved, the image may become distorted or cropped in an undesirable way.
Issues
Aspect Ratio is a test within a Best Practices audit in Lighthouse.
Reference: 📑 Display images with incorrect aspect ratio - Chrome for Developers
Here is an example Lighthouse report from DevTools where an image 🔺displays an incorrect aspect ratio.
How to Fix
There are a few ways to fix an incorrect aspect ratio:
- Use
aspect-ratio
declaration in CSS to define the desired aspect ratio using standard notation, e.g.,16 / 9
- Use the
width
andheight
attributes on the<img>
element to specify the dimensions of the image in pixels that match the instrinsic/orginial dimensions. - Use the
object-fit
property to specify how the contents of the<img>
element should be resized to fit its container.Here is an example of this error along with a solution using CSS object-fit on CodePen: ⚙️ object-fit