- Published on
Fix broken images automatically in HTML
- Authors
- Name
- Khalil
- @Im_Khalil
Broken images are ugly..
I will explain a couple of methods to fix broken images.
- Hide the broken image dynamically using jQuery
- Use CSS to style the broken image.
Using jQuery :
Hide the broken image, by adding the following attribute
<img src="Error.src" onerror="this.style.display='none'"/>
Replace the broken image with fall back image.
<img src="Error.src" onerror ="this.src='fallback-img.jpg'"/>
Using CSS:
To understand how we can style broken images, there are two facts about the way the <img>
element behaves that we need to understand first.
We can apply regular typography-related styling to the <img>
element. These styles will be applied to the alternative text, if it is displayed, and will not affect the working image. The <img>
element is a replaced element. This is an element “whose appearance and dimensions are defined by an external resource” (Sitepoint). Because the element is controlled by an external source, the :before
and :after
pseudo-elements typically shouldn’t work with it. However, when the image is broken and not loaded, these pseudo-elements can appear.
Because of these two facts, we are able to apply styles to the <img>
element that will only appear when the image is broken, and will leave a working image unaffected.
Time for practice:
One way we can handle broken images is to provide a message to the user saying that the image is broken. Using the attr() expression, we can even display the link to the broken image.
img {
font-family: 'Helvetica';
font-weight: 300;
line-height: 2;
text-align: center;
width: 100%;
height: auto;
display: block;
position: relative;
}
img:before {
content: "We're sorry, the image below is broken :(";
display: block;
margin-bottom: 10px;
}
img:after {
content: "(url: " attr(src) ")";
display: block;
font-size: 12px;
}
In addition to (or instead of) displaying a custom message, we can use the pseudo-elements to apply more styling to the broken image.
img {
/* Same as first example */
min-height: 50px;
}
img:before {
content: " ";
display: block;
position: absolute;
top: -10px;
left: 0;
height: calc(100% + 10px);
width: 100%;
background-color: rgb(230, 230, 230);
border: 2px dotted rgb(200, 200, 200);
border-radius: 5px;
}
img:after {
content: "\f127" " Broken Image of " attr(alt);
display: block;
font-size: 16px;
font-style: normal;
font-family: FontAwesome;
color: rgb(100, 100, 100);
position: absolute;
top: 5px;
left: 0;
width: 100%;
text-align: center;
}
If the image is not broken, with all the same styles applied to the element, the image is displayed normally. The pseudo-elements are not generated at all.
Khalil Ganiga
Just another programmer.. This blog expresses my views of various technologies and scenarios I have come across in realtime.
Keep watching this space for more updates.