In the first article covering selectors, we discussed the CSS group, universal, class and ID selectors. In this article, we continue our discussion of selectors with various attribute selectors.
Learn CSS, Selectors, part 2 - The Attribute Selector (Page 2 of 7 )
This is the simplest and most basic attribute selector. You can use it to apply certain styles to an element that has a specific attribute. This can be useful in many ways; for example, in XML the attribute selector can give a style to an element when it has a certain attribute, regardless of this attribute's value. Let's take a look. Below is an XML file (save it as Books.xml) followed by the CSS code (save this file as Selectors.css)
Open this XML document using a Web browser that supports attribute selectors, such as Mozilla 7.1 or Opera 7.5 (remember, IE doesn't support attribute selectors). You will get the following result:
The XML file contains the root element <Books>, which contains two <Book> elements. The first <Book> element contains the <Author> element, which has the Rank attribute. The following CSS syntax states that every time the <Author> element has the Rank attribute, the element will have a GreenYellow background and a blue color with an Arial font and a size of 90% of the default size font.
The syntax is very simple; after the element name, put the attribute inside brackets and you are done. Note that the second <Book> element doesn't have any style because there's no Rank attribute for this <Book> element. You can apply the styling rule if the element has more than one attribute, but the syntax will be different. Modify the XML document as follows:
As you can see, we have added the attribute Country inside [] to the Author attribute selector. If you reload the Web page, you will find the same formatting style. The same applies to HTML; we will see examples in the next sections.