Broken images are ugly things. They ruin the feel of a website instantly and give an unloved and uncared for look.

Besides actively going in and fixing the image path, which if you have a large website, could be a long and arduous task to track them all down, a quick remedy would be to style the images in case of a breakage.

The Method

<img src="https://www.madebymagnitude.com/broken.jpg" alt="MbM broken image!" />

Here we have an image that doesn’t exist. Usually it would appear as a broken icon with unstyled text for the alt tag. We can fix this though, through the power of CSS!

img { 
    font-family: 'Helvetica'; 
    font-weight: 300; 
    line-height: 2; 
    text-align: center; 
    width: 100%; 
    height: auto; 
    display: block; 
    position: relative; 
}

First we style the image and give it text properties.

We then utilise CSS Pseudo-elements ::before and ::after to make this styled to our site.

:before { 
    content: "f1c5" " " attr(alt); 
    font-size: rem-calc(16px); 
    font-family: FontAwesome; 
    color: rgb(100, 100, 100); 
    display: block;
    position: absolute; 
    z-index: 2; 
    top: 0; 
    left: 0; 
    width: 100%; 
    height: 100%; 
    background-color: #fff; 
}

The ::before contains the Alt text with a Font Awesome image icon before it (just make sure, if you want to use Font Awesome, to reference the CDN or self hosted file on your page before use).

The ::after contains the URL of the image so viewers can see exactly where the image was meant to reside.

Put that all together nested nicely in some SCSS, and now all of your images will be pretty, regardless of whether they actually exist or not! Neat, right?

Pulling it All Together

img { 
    font-family: 'Helvetica'; 
    font-weight: 300; 
    line-height: 2; 
    text-align: center; 
    width: 100%; 
    height: auto; 
    display: block; 
    position: relative; 
    &:before { 
        content: "f1c5" " " attr(alt); 
        font-size: rem-calc(30px); 
        font-family: FontAwesome; 
        color: rgb(100, 100, 100); 
        display: block; 
        position: absolute; 
        z-index: 2; 
        top: 0; 
        left: 0; 
        width: 100%; 
        height: 100%; 
        background-color: #fff; 
    } 
    &:after { 
        content: "(url: " attr(src) ")"; 
        display: block; 
        font-size: rem-calc(12px); 
        position: relative; 
        color: #00aeef; 
        bottom: -10px; 
        z-index: 1000;
    } 
}

The Result

stylised-broken-image.png

3