Tip - Styling Broken Images

Posted By Will Moody On , Reading Time - 2 minutes

Tips

Styling Broken Images

Broken image sources don't look good on a website, but sometimes an image is missing from the server and can’t be displayed. How can we make them a look nicer?

We can use CSS to apply styles to the <img> element to provide a better experience than the default.

Two Facts About The <IMG> Element

To understand how we can style broken images, there are two facts about the way the <img> element behaves that we need to understand first.

We can apply regular typography-related styling to the <img> element. These styles will be applied to the alternative text, if it is displayed, and will not affect the working image. The <img> element is a replaced element. This is an element “whose appearance and dimensions are defined by an external resource".

Because the element is controlled by an external source, the :before and :after pseudo-elements typically shouldn’t work with it. However, when the image is broken and not loaded, these pseudo-elements can appear.

Because of these two facts, we are able to apply styles to the <img> element that will only appear when the image is broken and will leave a working image unaffected.

Styling A Broken Image With CSS

Below is the effect we are aiming to achieve, a broken image but at least an explaination for the browser.

Broken image link with no styling

We can apply our CSS styling like this:-

img {
    font-family: Arial, sans-serif;
    font-size: 16px;
    line-height: 1.5;
    text-align: center;
    width: 100%;
    height: auto;
    position: relative;
}

img:before {
    content: "We're sorry, the image below is broken";
    display: block;
    margin-bottom: 10px;
}

img:after {
    content: "(url: " attr(src) ")";
    display: block;
    font-size: 0.75em;
    margin-top: 6px;
}

We can improve the styling a bit if it's considered necessary to acheive this effect.

Broken image link with extra styling

img{
    font-family: inherit;
    font-size: inherit;
    line-height: inherit;
    text-align: center;
    width: 100%;
    height: auto;
    position: relative;
    min-height: 50px;
}

img:before {
    content: " ";
    display: block;
    position: absolute;
    top: -10px;
    left: 0;
    height: calc(100% + 20px);
    width: 100%;
    background-color: rgb(230, 230, 230);
    border: 2px dotted rgb(200, 200, 200);
    border-radius: 5px;
}

img:after {
    content: "\f057"" Broken Image of " attr(alt);
    display: block;
    font-size: inherit;
    font-style: normal;
    font-family: "Font Awesome\ 5 Free";
    font-weight: 900;
    color: rgb(100, 100, 100);
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    text-align: center;
}

Source: Bitsofco

PS:- A small side tip, is that using the latest version of FontAwesome which in this case is 5, you may have to use a font-weight of 900 to get the icons to show correctly.

Working Codepen Example: follow this link