Today I Learned

How to style broken images in CSS (and a bit of JS)

When working on a client’s website, I’ve spotted some images looking like that:


Turns out there are ways to change how the broken images look, but it’s a bit different for every browser, you can apply styles like background-color to:

  • the image itself,
  • the ::before element of the image,
  • using special selectors for not working images,
  • or you need to use the onerror property (or some other form of detecting a broken image in JS).

Click to see examples of how to deal with broken images, and run the examples in Chrome/Firefox/Safari to see the differences.