Skip to main content
CSS Tip

How to style a broken image

When an image fails to load the browser will simply show you the alt text but you can change this using a cool CSS trick. Broken images accept pseudo-elements such as ::before and ::after so we can tweak them to add a custom error message or any visual you want.

Custom error message for broken images

img {
position: relative;
}
img::after {
content: "We failed to load the image of \A'" attr(alt) "'\A 😞"/"";
position: absolute;
inset: 0;
display: grid;
place-items: center;
text-align: center;
border: 2px dashed;
font: bold 1.6em/1.5 system-ui;
white-space: pre-wrap;
}

The above style will not apply to correctly loaded images so no need for any specific selector to exclude them

See the Pen Style broken images by Temani Afif (@t_afif) on CodePen.


More CSS Tips