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:
[attribut]– The rule applies to all elements containing the specified HTML attribute.[attribut="wert"]– The rule applies to all elements with exactly this attribute-value combination. No other values may be assigned to the attribute.[attribut~="wert"]– The rule applies to all elements with exactly this attribute-value combination, but the attribute may also have other values.[attribut|="wert"]– The rule applies to all elements with this attribute-value combination. The value must come first, and subsequent values must be joined by hyphens.
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.
Copyright © 2006 of the German translation, dpunkt.verlag GmbH
You may print the online version for your private use.
Otherwise, this chapter from “CSS − Anspruchsvolle Websites mit Cascading Stylesheets” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
dpunkt.verlag GmbH, Ringstraße 19, 69115 Heidelberg
back to top