Displays an error message when an image fails to load.
- Apply styles to the
img
element as if it was a text container. - Use the
::before
and::after
pseudo-elements to display an error message and the image URL. These elements will only be displayed if the image fails to load.
预览
HTML
<img src="https://nowhere.to.be/found.jpg" />
CSS
img {
display: block;
font-family: sans-serif;
font-weight: 300;
height: auto;
line-height: 2;
position: relative;
text-align: center;
width: 100%;
}
img::before {
content: "Sorry, this image is unavailable.";
display: block;
margin-bottom: 8px;
}
img::after {
content: "(url: " attr(src) ")";
display: block;
font-size: 12px;
}
翻译自:https://www.30secondsofcode.org/css/s/broken-image-fallback