New CSS to fix Chrome breaking old CSS (image size/aspect ratio)

Last week I had several clients report to me that their websites were suddenly displaying images at the wrong size — too small. I checked their sites (in Safari, my default browser), and everything looked fine.

Then I realized, it was a bug in the new version of Chrome. (At least, it seems like a bug to me, when CSS code I’ve been using consistently for over a decade suddenly doesn’t render properly in just one browser, right after that browser has been updated.)

Here’s the code I had been using:

img {
  height: auto;
  width: auto;
  max-width: 100%;
}

I discovered that by just removing the width: auto; line, the images rendered at the intended size, and this didn’t seem to break anything in other browsers either. Sweet!

Unfortunately today I had a client contact me with what I initially thought was the same issue. But then they said it was affecting Firefox and Edge as well. (Windows user!) Sure enough it’s also a problem in Safari.

But this time, it’s not that the images are rendering too small; it’s that they’re getting stretched and distorted. Then I realized I had already applied my fix for that client’s site, and it was causing this new issue.

Fortunately there’s another simple CSS fix. (I briefly considered the aspect-ratio property, but that’s not flexible enough for what I’m trying to do.) It’s a newer CSS property that I haven’t used much: object-fit.

It’s really quite simple though. Here’s the new code I’m using that seems to resolve the issue completely. But I suppose I’ll get another email from someone next week describing another edge case where it doesn’t work. Stay tuned…

img {
  height: auto;
  max-width: 100%;
  object-fit: contain;
}

Update (11/21/2024): OK, so maybe as with the PNG-to-HEIC-to-JPEG glitch, this was actually more of a WordPress 6.7 issue. By the way, I reported the PNG glitch and it got patched in 6.7.1, as did this issue… assuming it’s the same issue I’m describing here, which kind of sounds like it. In retrospect it does seem kind of odd that Chrome and WordPress would both introduce image-related issues on the same day. Much more likely that WordPress introduced multiple issues — or, well, maybe just revealed browser issues, but still. Gotta blame someone.