Matthew Roach

Valid ALT text?

Tip: highlight images missing alt text with img:not([alt])

— Addy Osmani (@addyosmani) February 2, 2020

This tweet the other day from Addy Osmani showing some CSS on how to highlight images on a page with no alt attribute got me thinking. Addy’s tip is great and shows how developers can provide guidance within the apps/sites they are building to editors/admins on missing attributes that are required for accessibility. The part I was stuck on was this only shows what I would call error states, there is also the state where the alt attribute can be present meaning the red border isn’t shown, this can provide false positives as even though a blank alt attribute is valid. It is only valid for decorative image. For frameworks like React or others it’s possible to put yourself outside of the error state easily without knowing it, and it appears like you are valid. A much better tip would be to highlight the “decorative” state image with a warning – using an orange or so forth. This then allows the user to quickly check the images that are present and have an alt attribute but not value and gives them the opportunity to confirm if that’s the correct state for the given image.

For example in a web application where a developer is using a utility function to display and image/graphic and assumes the alt text is being set based on them passing a value, or even if they are just passing an object of data from a API or other datasource. Example of a CMS, where the UI is built in React and you just pass the image data from the API into your component – the issue here is you are hoping the admin/editor added the alt text in the photo/media library tool.

Having images that are non decorative with a blank/null alt text fails accessibility for WCAG 1.1.1 Non-text Content – H67: Using null alt text and no title attribute on img elements for images that AT should ignore.

// Error - missing alt
img:not([alt]) {
    border: 5px solid rgb(255, 0, 0);

// Warning - Has alt attribute but no text value img[alt=''] { border: 5px solid rgb(255, 165, 0); }

The following CSS is used to produce the output you see in the image below. I also put together a quick demo over to provide a working example:


Demo of highlight alt missing and alt blank