October 29, 2021

Implicitly using the aspect-ratio CSS property on images in HTML emails

The aspect-ratio CSS property is supported across all major browsers now:

Data on support for the mdn-css__properties__aspect-ratio feature across the major browsers

But most major email clients still do not support it:

Yet, you can rely on it for images! Set the width and the height attributes on the img tag, and the browser handles the rest:

<img src="https://via.placeholder.com/1200x675/FF0000/FFFFFF.png" alt="" width="1200" height="675" style="width:100%; height:auto;" />

This works because the browser's user agent style sheet utilises the values of the width and height attributes to generate the value for the aspect-ratio property:

img {
  aspect-ratio: attr(width) / attr(height);
}

At the time of writing, the attr() function can only be used on the content CSS property. However, when it comes to the browsers UA style sheet the browser can map these values "under the hood" but the CSS value is still represented using the same attr() function.

If you're unfamiliar with the problems aspect-ratio solves, check:

Web vs Email

On a normal web page, it doesn't matter what the values for the width and height attributes are as long as the generated formula represent the same value. So for a 16:9 image, all the below are rendered the same way in modern browsers:

<img src="https://via.placeholder.com/1200x675/FF0000/FFFFFF.png" alt="" width="16" height="9" style="width:100%; height:auto;" />
<img src="https://via.placeholder.com/1200x675/FF0000/FFFFFF.png" alt="" width="640" height="360" style="width:100%; height:auto;" />
<img src="https://via.placeholder.com/1200x675/FF0000/FFFFFF.png" alt="" width="1200" height="675" style="width:100%; height:auto;" />

Unfortunately, in email clients it's not as straightforward because:

  1. Outlook Windows still render HTML emails using Microsoft Word, not a browser engine.
  2. Gmail's desktop basic HTML view rewrites the height property to min-height.

So unlike on a normal page, it matters which values are used for the width and height attributes. Using the largest values at which you intend to render the image seems a safe approach. So if you have a 1200px x 676px image, but the largest size at which the image is going to be rendered in your email is 640px x 360px, you'd use:

<img src="https://via.placeholder.com/1200x675/FF0000/FFFFFF.png" alt="" width="640" height="360" style="width:100%; height:auto;" />