in Crafts

Prevent Object-fit polyfill from messing with broken image’s alternative text styling

That is a hell of a long title for a very short post.

If you’re using the Object Fit Images Polyfill you might have noticed that broken images’ alt texts render in Times New Roman. This happens because Object Fit Images  works by setting a faux font-family on the image, which is then used by JavaScript. The problem is that the browser tries to render a broken image’s alt text which, of course, doesn’t exist. So it falls back to whatever the browser uses as default. 

To prevent this we can simply add inherit to our font-stack of the image: 

// When using Object Fit Images Manually
img {
object-fit: cover;
font-family: "object-fit:cover", inherit;
}

So what if you’re using PostCSS Object Fit Images to automatically add that font family to any selector that employs object-fit? Luckily it respects any existing font declaration and adds it to the font stack. So we can simply add the inherit statement directly:

// When using PostCSS Object Fit Images 
img {
object-fit: cover;
font-family: inherit;
}

The result in both cases is: font-family: "object-fit:cover", inherit; and allows for the polyfill to do its thing while at the same time setting the font-family to the one used in the next proximate parent.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Related Content by Tag