Style broken images
Written byPhuoc Nguyen
Created
23 Feb, 2021
Last updated
27 Feb, 2021
Category
Tip
Tags
CSS
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.css
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
html
<img src="/assets/img/not-found.png" alt="front-end tips" />
Questions? 🙋
Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
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