Force Alt Text with CSS

Con­tent man­age­ment sys­tems with WYSIWYG edi­tors are great tools, in that they enable easy pub­li­ca­tion by those not famil­iar with HTML. But that same ease of use may enable non-​​valid or inac­ces­si­ble HTML markup. Some CSS rules have been sug­gested by oth­ers to enforce good markup by penal­iz­ing bad markup. For instance, use of depre­ci­ated tags can be forced to dis­play as big, bold and red:

font {
    font-size: 50px;
    font-weight: bold;
    color: red;
}

You may view this as overly con­fronta­tional. But I just con­ceived a way to use CSS (with a bit more con­straint), to enforce acces­si­ble markup. One of the most impor­tant acces­si­ble prac­tices (and eas­i­est to imple­ment) is the inclu­sion of alter­nate text for images. The fol­low­ing HTML demon­strates proper inclu­sion of the required alt attribute.

<img src="/pic.jpg" alt="Jeff's mug" />

If some­one uses a con­tent man­age­ment sys­tem to dis­play an image that is miss­ing this attribute, you can use your CSS stylesheet to sup­press the image from dis­play­ing with the fol­low­ing code:

img {
    visibility: hidden;
}
img[alt] {
    visibility: visible;
}

A few thoughts result from this imple­men­ta­tion. Not every screen reader will ignore hid­den ele­ments, but that is not the point. If an image is not acces­si­ble to every­one (by way of an alt tag), this ensures that the pub­lisher of the con­tent rec­og­nizes that same inaccessibility.

Sec­ond, visibility is used for sev­eral reasons.

  • It does not con­flict with your other display rules that may give images inline or block value in dif­fer­ent context;
  • visibility leaves a void of con­tent, mak­ing it clear to the pub­lisher that the image is not dis­play­ing; and
  • display can be turned off with a value of none, but there is no valid value for turn­ing it back on (with­out con­tex­tual knowl­edge of whether block or inline is appropriate).

Lastly, this pro­posal breaks in Inter­net Explorer 6, as IE6 does not under­stand attribute selec­tors. This can be resolved with the inclu­sion of con­di­tional com­ments in your doc­u­ment head. For example:

<!--[if lt IE 7]>
    <style>
        img {
            visibility: visible;
        }
    </style>
<![endif]-->

Now images will dis­play as nor­mal in IE6.

Jeffrey D. King

About the Author

Jef­frey D. King is a web designer and con­sul­tant in San Diego. Jeff is pas­sion­ate about the inter­sec­tion of busi­ness and the inter­net. As a stu­dent of design, usabil­ity, brand­ing, and entre­pre­neur­ial strate­gies, he can help your orga­ni­za­tion achieve online success.

Leave a Comment

Please note our comment and privacy policies.

(required)
(required)