Styling Image Alt Text

When an image fails to load, if it has alt text then this will be displayed instead. In some situations it may be desirable to distinguish alt text from the main text content of the page.

This can be achived by applying styles to the img element, perhaps a colour or font size change.

img {
  color: grey;
}

Furthermore a pseudo-element can be used to clearly state that the text represents an image which failed to load.

img::before {
  content: 'Image (' attr(src) ') failed to load: ';
  color: red;
}

When adding a pseudo-element like this we need to ensure that it will not be added to images without an alt attribute or with an empty alt attribute as the pseudo-element only exists to explain the presence of the alt text and should not appear on its own.

img[alt]:not([alt=""])::before {
  content: 'Image (' attr(src) ') failed to load: ';
  color: red;
}

Here is a demo showing this in action.

CSS
SCROLL TO TOP