How to hide image broken Icon using only CSS/HTML?
Nullify the broken image icon in HTML by adjusting an img
element’s display
to none
when its source is unavailable. Here's the salient CSS recipe:
This insulation mechanism ensures images are visible only when properly loaded. In case of failure, they're hidden, thereby preventing unsightly corrupted icons.
Eliminating the void through CSS
Instead of leaving empty spaces where images failed to load, we can implement an elegant placeholder using CSS to maintain layout integrity:
The object
é d'art solution
If you're fond of graceful degradation, consider using the <object>
tag as the container for your images:
This falls back to an embedded object such as a fallback image or, in its absence, disintegrates gracefully without rendering anything.
More power to you with onerror
While the pure CSS solutions are appealing, if you’re open to injecting a touch of JavaScript, an onerror
attribute can offer even greater control:
With this, JavaScript only springs into action when an error happens, thus preventing any unnecessary changes to your initial CSS.
Using CSS to play hide and seek
Here's our geeky prank. With the text-indent property, we shove the broken image icon offscreen:
Each image saved from displaying a broken icon contributes to a cleaner, professional design.
Serving aesthetics with pseudo-elements
The ::after
pseudo-element is your ally in this mission. It covers up the broken image, leaving no evidence behind:
Ensuring safe display with CSS
Lastly, let's ensure the safety of your object
tag usage by verifying the sources:
This adds a layer of security while keeping your design aesthetic intact.
Was this article helpful?