CSS attribute selectors - clever styling
I wrote this post a while back. The content can still be relevant but the information I've linked to may not be available.
I am reading CSS Mastery [the book] [the website] by Andy Budd at the moment. After reading the first chapters and a few other pages, I have already come across an interesting CSS usage that I should have been more aware of. The attribute selector is its name. To get to the point, the attribute selector allows you to style any web page element based on an attribute and, more interestingly, the attribute value (or partial value). In its simplest form the attribute selector and CSS code might be:
element[attribute] {CSS rule goes here} or
element[attribute="value"] {CSS rule goes here}
For example, the attribute selector will allow you to style all external links without modifying the HTML. This CSS code in your style sheet will give all external links a background color of yellow:
a[href^="http:"] {
background-color: #FF0;}
Cool. Well, perhaps not this shade of yellow (a background image is probably better), but you get the idea. In this case, the attribute selector, a[href^="http:"], selects all <a> elements with an href value starting with "http:". Of course, if you are using absolute links to your own site, you will need to add another rule for any links beginning with "http://www.yoursitename".
Other uses for the attribute selector might include styling document links (for example, PDF documents) and use with microformats.
At this point, I would normally be saying "except for Internet Explorer". However, newly released IE7 has support for the attribute selector. Great! It may be time to start using attribute selectors more.
Comments are OFF for this post.