Simple attribute selectors allow you to target an element for styling based on the existence of an attribute.

General Syntax for the Simple Attribute Selector

element[attr] { declarations... }

This selector is not supported in Windows IE 6 or below.

The first part of the selector is the name of the element, while the second part of the selector is the name of the attribute in brackets. You may only specify one attribute in the selector.

As you know, the CSS standard requires that all images include the ALT attribute to describe the image. This is for accessibility, allowing a screen reader to describe the image for visually impaired users, and to substitute the image for the ALT text if a browser is not capable of displaying images. Suppose we want to visually ensure that all images on our site have included the ALT attribute. This example shows how we can use the simple attribute selector to help us test for that. Here's how:

Example Style sheet

img[alt] { border: 5px solid green; }

The rule specifies that any IMG which has an ALT attribute will have a thick green border. Using the simple attribute selector, we can highlight all images with a thick green border if they specify the ALT attribute. CSS enables us to do this site-wide with a single rule in the style sheet!

Example Markup

<img src="images/logo-QT.jpg" alt="logo-Quicktime" /> <img src="images/logo-realPlayer.gif" /> <img src="images/logo-reader.gif" alt="logo-Reader" />

Rendered Example

logo-Quicktime logo-Reader

Notice that a thick green border was not applied to the center image. This clearly indicates that the center image does not include the ALT attribute and, therefore, will not validate.

CSS doesn't limit attribute selectors to tag names. You can combine attribute selectors with classes, too.

The following example applies a red border to any tag that has the "gallery" class attached to it, and includes a TITLE attribute:

.gallery[title] { border: red 5px solid }

Example Markup

<p> <img src="images/logo-windmill.gif" alt="windmill logo" width="100" height="85" />   <img title="quicktime logo" src="images/logo-QT.jpg" alt="quicktime logo" width="72" height="72" />   <img class="gallery" src="images/cloud.jpg" alt="clouds" width="113" height="85" />   <img class="gallery" title="cute black kitty" src="images/kazul.jpg" alt="lounging black kitty" width="143" height="85" /> </p>

windmill logo quicktime logo clouds lounging black kitty