Is there any way to render a default image in an HTML
tag, in case the src
attribute is invalid (using only HTML)? If not, what would
An HTML only solution, where the only requirement is that you know the size of the image that you're inserting. Will not work for transparent images, as it uses background-image
as a filler.
We can successfully use background-image
to link the image that appears if the given image is missing. Then the only problem is the broken icon image - we can remove it by inserting a very big empty character, thus pushing the content outside the display of img
.
img {
background-image: url("http://placehold.it/200x200");
overflow: hidden;
}
img:before {
content: " ";
font-size: 1000px;
}
This image is missing:

And is displaying the placeholder
An CSS only solution (Webkit only)
img:before {
content: " ";
font-size: 1000px;
background-image: url("http://placehold.it/200x200");
display: block;
width: 200px;
height: 200px;
position: relative;
z-index: 0;
margin-bottom: -16px;
}
This image is there:

This image is missing:

And is displaying the placeholder