Being more accessible: Highlighting images that don't have alternate text

I saw a tweet recently that showed a really cool trick you can use to highlight when images are either have missing, or empty, alternate text. As Wikipedia says (so it must be true!):

The alt attribute is used by "screen reader" software so that a person who is listening to the content of a webpage (for instance, a person who is blind) can interact with this element. Every image should have an alt attribute to be accessible, but it need not contain text. It can be an empty or null attribute

I've highlighted one part of the text from Wikipedia that mentions that the alt attribute doesn't have to contain anything, the purpose of this example code is to ensure that if it is absent, or empty, the developer/designer sees that fact and can react to it. The CSS snippet is quite small, simple and really very elegant:

img[alt=""],
img:not([alt])
{
    border: 5px dashed #c00;
}

All it does is utilises two selectors, one for an image with an alt attribute that contains no text, and one for an image with no alt attribute. This means that if you have some markup that looks like this (using some images I grabbed from the folder I store all the images I create for my blog):

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Missing ALT tester</title>
    <link href="styles.css" rel="stylesheet" />
</head>
<body>
    <img src="images/azure_storage_blob_metadata_tophat.PNG" alt="This image has an alt tag" />
    <br />
    <img src="images/azure_storage_emulator_cortana.png" alt="" />
    <br />
    <img src="images/missing_taskbar.PNG" />
    <br />
    <img src="images/outlook_sorry.PNG" />
    <br />
    <img src="images/reduced_number_of_structured_data_items.PNG" />
    <br />
    <img src="images/vnet_in_dashboard.PNG" />
</body>
</html>

When this page is loaded, assuming you have the images for it, you'll see six, one on top of the other, but all the images except the first one will have a fat red dashed border around them. This makes it immediately apparent that the last five images either have no alt attribute, or the attribute is empty:

Images showing that the alternate text CSS trick highlights ones that don't have an alt attribute

What a neat trick!

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment