What are the four types of attribute selectors?
Author: Deron Eriksson
Description: This CSS example demonstrates the four types of attribute selectors.
Tutorial created using: Windows XP


Page:    1 2 >

According to the CSS2 specification ( http://www.w3.org/TR/REC-CSS2/Overview.html ), there are four types of attribute selectors: [att], [att=val], [att~=val], and [att|=val]. The first attribute selector allows for the selection of an element based on the presence of the attribute. The second attribute selector allows for the selection of an element based on the presence of an attribute and an exact value for that attribute. The third attribute selector allows for the selection of an element based on the the value of an attribute, where the attribute value contains multiple space-separated words, and the attribute selector matches one of those words. The fourth attribute selector allows for the selection of an element based on the value of an attribute, where the attribute value can contain multiple hyphen-separated words, and the attribute selector matches the first word. This last attribute selector is useful primarily in conjunction with the "lang" attribute.

The style-test.html file demonstrates these four types of attribute selectors. The 'h2[align]' selector selects based on the presence of the align attribute. The 'h2[align="center"]' selector selects based on the presence of the align attribute with a value of "center". The 'h2[class~="blah"]' selector selects based on the presence of the class attribute with one of its classes being equal to "blah". The 'h2[class|="bacon"]' selector selects based on the presence of the class attribute with a value (in a hyphenated set of words) that starts with "bacon".

style-test.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Style Test</title>
<style type="text/css">
h2[align] { background: yellow; }
h2[align="center"] { color: red; }
h2[class~="blah"] { color: green; }
h2[class|="bacon"] { color: orange; }
</style>
</head>
<body>
<h2>Howdy One</h2>
<h2 align="left">Howdy Two</h2>
<h2 align="center">Howdy Three</h2>
<h2 class="hmm blah ok">Howdy Four</h2>
<h2 class="bacon-eggs">Howdy Five</h2>
</body>
</html>

The output of style-test.html in IE7 is shown below.

attribute selectors example

(Continued on page 2)

Page:    1 2 >