By default, the browser will display a placeholder for a broken image. This post introduces a simple tip to replace that placeholder with our stylable elements.
When the image is not found, the `::before`
and `::after`
pseudo-elements are displayed as long as they have content. We can take this advantage to make these elements visible to the user.
img {
position: relative;
display: block;
height: auto;
min-height: 4rem;
width: 100%;
}
img::before,
img::after {
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}
img::before {
background: #fff;
content: '';
}
img::after {
content: attr(alt) ' image is broken';
border: 2px dotted #d1d5db;
align-items: center;
display: flex;
justify-content: center;
}
Demo
The demo below shows extra elements for a broken image whose markup is
<img src="/img/not-found.png" alt="front-end tips" />