DEV Community

Stephen Afam-Osemene
Stephen Afam-Osemene

Posted on • Edited on • Originally published at stephenafamo.com

2 1

The best way to style broken images

Most techniques to style broken images rely on browser hacks and are very inconsistent. Let me show you a consistent way that works the same way across every browser.

This technique relies on the HTMLMediaElement.onerror property, which is supported in almost every browser, all the way back to IE9. Take a look:

On all our images, we will add an onerror event handler which will change the src of our image to a predefined one

<img src="/path/toimage" alt="my image" 
onerror="this.onerror=null;this.src='/broken-img.svg';this.classList.add('broken-img');">
Enter fullscreen mode Exit fullscreen mode

What’s happening here?

We are hooking into the onerror event which fires when some form of error occurs while attempting to load or perform the media. When the event fires, we replace the src of the image to point to A NEW image and adds the class broken-img to our image.

On Swish, I use this image, an SVG that is only 855B in size, and will be loaded once no matter how many times it appears on the page.

This part this.onerror=null prevents the browser from falling into an infinite loop if the onerror handler has a problem, maybe if the new image was also unable to be loaded. Although some browsers evaluate the onerror handler just once, others will attempt to run it again and again if an error keeps occurring.

With the broken-img class, we can add any further styling that only applies when the image is broken. On Swish, I limit the height of the image to 5em

.broken-img {
    max-height: 5em;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

I think this is the best way to handle broken images, we use a system that is guaranteed to work the same way across browsers and has practically no adverse effects on our website’s peformance.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay