← Back toFront-end Tips

Style broken images

Written byPhuoc Nguyen
Category
Tip
Tags
CSS
Created
23 Feb, 2021
Last updated
27 Feb, 2021
Contributors
KittyGiraudel
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;

/* The initial styles */
display: block;
height: auto;
min-height: 4rem;
width: 100%;
}

img::before,
img::after {
/* Take full size of the image */
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}

img::before {
/* Hide the default placeholder */
background: #fff;
content: '';
}

img::after {
/* Taken from the `alt` attribute of the element */
content: attr(alt) ' image is broken';
border: 2px dotted #d1d5db;

/* Center */
align-items: center;
display: flex;
justify-content: center;
}
The demo below shows extra elements for a broken image whose markup is
<img src="/assets/img/not-found.png" alt="front-end tips" />

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn