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)
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="Selectors.css"?>
<Books>
<Book>
<title>Programming Microsoft ASP.NET</title>
<Author Rank="5">Dino Esposito</Author>
</Book>
<Book>
<title>Inside C#</title>
<Author>Andrew Whitechapel</Author>
</Book>
</Books>
The CSS code:
Author
{
display: block;
}
Author[Rank]
{
color: Blue;
background-color: YellowGreen;
font-size: .9em;
font-family: Arial, Tahoma;
display: block;
}
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.
Author[Rank]
{
color: Blue;
background-color: YellowGreen;
font-size: .9em;
font-family: Arial, Tahoma;
display: block;
}
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:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="Selectors.css"?>
<Books>
<Book>
<title>Programming Microsoft ASP.NET</title>
<Author Rank="5" Country="Italy">Dino Esposito</Author>
</Book>
<Book>
<title>Inside C#</title>
<Author>Andrew Whitechapel</Author>
</Book>
</Books>
We have added the attribute Country to the <Author> element. Now modify the CSS code as follows:
Author
{
display: block;
}
Author[Rank][Country]
{
color: Blue;
background-color: YellowGreen;
font-size: .9em;
font-family: Arial, Tahoma;
display: block;
}
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.
Next: Specific-Value Attribute Selector >>
More Style Sheets Articles
More By Michael Youssef