html css

Using CSS to highlight images not containing the 'alt' attribute

Feb 9, 2020

Use CSS to highlight any images within our webpage that does not have the alt attribute. This will help us improve the accessiblity of our web site.

In this post, we will use CSS to highlight any images within our webpage that does not have the alt attribute.

Background and what is the alt attribute?

If we want our site to be accessible, then we should include the alt attribute on all important images. An alt attribute is a alternate text for a image. It will appear if the image has not loaded or can be used by vision impared users with screen readers. The screen readers will read the alt text out loud to help the users understand what that image is about.

<img src="book.gif" alt="A image of a book" />

Why would I want to do this?

Sometimes when working on a large website theres a chance that we will miss adding the alt attributes to our image tags. To highlight which image on the page does not have the alt attribute, we can use the following CSS rule:

img[alt=""], img:not([alt]) {
    border: 3px solid #f00;
}

The above finds all images with no alt attribute or only contains empty string. Also keep in mind that the above acts as a warning. We will still need to go case-by-case for each element to determine if a img is accessible or not. For example, if we have a image wrapped in a link and the link text describes the image:

<a><img src="book.png" role="presentation" alt="" />This is a book</a>

Even though we have empty alt here, this is deemed accessible since the text gives a description of the image. Additionally sometimes images that are intendend for just decoration can get away with not including the alt text.

Hope this helps.