CSS Selectors – a real world example
Today a co-worker of mine had a simple problem that he wanted some help with. He needed to find all the “a” tags within a specific div, and if its href attribute ended in .pdf, then add a background image to it. I am going to guess that most people would just go and add a class to all the “a” tags that needed the image. That just puts more html on the page, when you can effectively do this with just some css.
Take into account, this example that we used today, works in all modern browsers, but not IE6-. Worked in IE7, so that was a good plus.
Here is the css:
#divId a[href$=".pdf"] { background-image: url(../images/imageName.gif); }
This says get the div with whatever id you are looking for, with an “a” tag, that has an “href” attribute that ends with exatly “.pdf”, and add the background-image to it.
I then did the same thing but for all links that got to “.docs”, and displayed a different image. So the second style was:
#divId a[href$=".doc"] { background-image: url(../images/imageName2.gif); }
If you actually wanted to hit ALL the “a” tags within the site like that, just remove the #divId from the style.
Tags: CSS






This is really cool. I just recently learned about CSS selectors, but the author could not provide a context in which it would actually be useful. This puts things into perspective. I’ll keep my eyes open for chances to use this. Sometimes it’s tough having so many tools available to you, you know? It’s knowing when to use what that gives me problems.
First let me say, thank you for being one of the first comments on my newly designed blog. In doing so, I got to see a css problem that I had to correct on the leave a reply pages.
Glad you found this useful. I’ve only had to use selectors in my sites a few times. One important one was in my old blog design:
div[id] {
properties here
}
This was because what I was working on was creating divs dynamically, and the classes and ids were different depending on the page. The order would stay the same though. The one I needed to target happened to be the only one with an id. The style above technically hits ALL divs with id’s, so I was able to be more specific with something like this:
#contentContainer div[id]
Selectors come in handy, but I haven’t had to use them all too often.