I'm working on an update to one of my projects and I had need of attribute selectors. If you've not used them before, they make CSS life so much easier. Attribute selectors allow developers to attach styles to an element based on the attributes (you got it) of the element. Let's look at some quick examples.
- table[width='130'] matches tables with a width of 130
- img[alt='ibm'] matches imgs with an alt of ibm
- a[href='https'] (see below)
Some of those might makes sense to you without much work, but that last one might catch you up. It's sort of like regular expressions. That last one matches any anchor tag with an href attribute that begins with https. There's a few more that are tricky, but useful too:
- [rel*='external'] matches items with external anywhere in the attribute
- [rel$='external'] matches items with external at the end of the attribute
- [rel~='external'] matches items with external in a space separated list
You can also use multiple attribute selectors together for even more sexiness:
- img[width='18'][height='18'] matches images with width and height of 18
So get your head out of the clouds and start using attribute selectors. Your code will thank you for it.
If this article was interesting, or helpful, or even wrong, please consider leaving a comment, or buying something from my wishlist. It's appreciated!
This is one of those CSS "tricks" that everyone has forgotten about because of having to support IE6 for so long. I especially love this selector for adding default styles to form controls based on their type. One thing to note, the width and height attribute selectors you have will only match the attribute value, not the CSS width or the current width value at the time.
And it looks like you're missing the caret in the href attribute selector in the example. Maybe your code highlighter has a hankering for vitamin A?
Shane Riley - May 18, 2012 03:48 am