O'Reilly logo

Cascading Style Sheets: The Definitive Guide, Second Edition by Eric A. Meyer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Attribute Selectors

When it comes to both class and ID selectors, what you’re really doing is selecting values of attributes. The syntax used in the previous two sections is particular to HTML, SVG, and MathML documents (as of this writing). In other markup languages, these class and ID selectors may not be available. To address this situation, CSS2 introduced attribute selectors, which can be used to select elements based on their attributes and the values of those attributes. There are four types of attribute selectors.

Warning

Attribute selectors are supported by the Opera and Gecko browsers but not by Internet Explorer through IE5/Mac and IE6/Win.

Simple Attribute Selection

If you want to select elements that have a certain attribute, regardless of the attribute’s value, you can use a simple attribute selector. For example, to select all h1 elements that have a class attribute with any value and make their text silver, write:

h1[class] {color: silver;}

So given the following markup:

<h1 class="hoopla">Hello</h1>
<h1 class="severe">Serenity</h1>
<h1 class="fancy">Fooling</h1>

you get the result shown in Figure 2-10.

Selecting elements based on their attributes

Figure 2-10. Selecting elements based on their attributes

This strategy is very useful in XML documents, as XML languages tend to have element and attribute names that are very specific to their purpose. Consider an XML language that is used to describe planets of ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required