andyMatthews.net

A quick look at CSS attribute selectors

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.