XML technologies / CSS / Advanced websites with CSS / Behind the scenes / Selectors and CSS rule structure / Attribute selectors

(Excerpt from “CSS − Advanced websites with Cascading Stylesheets” by Rachel Andrew & Dan Shafer)

The next group, which I simply call attribute selectors, includes some of the most interesting CSS selectors in my view, since using them is almost a programming technique. Each attribute selector specifies in its own way that a style rule applies only to elements containing a particular attribute or attribute-value combination.

There are four variants of attribute selectors:

The following rule uses the second variant to give all single-line text input fields <input type="text" /> white text on a black background:

input[type="text"] {
  color: white;
  background-color: black;
}

The third variant targets attributes containing a particular value either on its own or in a list of other values.

This is useful, for example, when several designers work on a website and use attributes alt in elements img as temporary placeholders for images. The following rule clearly marks the places where images will later appear:

img[alt~="Platzhalter"] {
  border: 8px solid red;
}

This rule gives all elements img whose attributes alt contain the word Platzhalter a conspicuous eight-pixel border. Hard to miss!

The fourth variant is useful only with the attribute lang, using values such as en or de. It can also specify regional dialects: en-us for American English, en-uk for British English, and so on. The selector [attribute|="value"] isolates the first part of the attribute lang. Further values after the hyphen are ignored.

As you probably expected, Internet Explorer 6 for Windows does not support attribute selectors. Like the other advanced selectors, they therefore have very limited practical applicability despite being very useful.

  

 

 

 

back to top