CSS Attribute Selectors: How and Why You Should Be Using Them

by on 13th July 2011 with 20 Comments

Today we’re going to learn about Attribute Selectors. What are they? How do I use them? What are the new CSS3 Attribute selectors? We’ll answer these questions and more.

HTML Attributes

Before I introduce you to the concept of CSS attribute selectors, you should know what an HTML attribute is. The good news is, you’re already familiar with several of them: class, id, style, and href for example. There are a ton more though, check out W3.org for a complete list.

CSS makes styling some attributes easy. For instance, if we want to style an id or class, we just use the following.

#someid {color: black}
.someclass {color: black}

This is all well and good, but what if we want to style some other attributes? This is where attribute selectors come into play.

Attribute Selectors

As we just learned, attribute selectors are exactly what they sound like, a way to select and target specific attributes using CSS. This is actually really easy to do and just involves a set of brackets containing the HTML that you used. Let’s see how this works by looking first at some basic HTML.

Let’s say I wanted to target and style only the Design Shack link. I could use pseudo selectors, but this assumes the list stays in that order and browser support isn’t the best. Instead, what we can do is use an attribute selector to target the specific “href” that we’re interested in.

a[href='http://designshack.net/'] {color: blue;}

screenshot

Repeating Attributes

Another example that’s used a lot is a list of contacts, one or more of which should be styled a certain way. Using attributes, we can differentiate between friends and contacts.

We can then go in and style each of these rel attributes differently using the same syntax as above. Much like with a class, multiple items can meet the criteria in one declaration.

li a[rel='friend'] {font-weight: bold;}
li a[rel='contact'] {font-weight: 200;}

Using this code we can achieve the results below. Notice that even if we start adding in new contacts to the top of the list, these selectors will still work where :nth-child wouldn’t. Pretty cool right? Further, just about every current browser supports these, including IE back to version 7!

screenshot

It’s also important to note that you don’t have to be so specific. The following will style any element with a rel attribute applied.

li a[rel] {font-weight: bold;}

Handling Multiples Values

The tricky part about using Attribute selectors is that they get a little funny when there is multiple attributes. Consider the following tweak to our previous list.

You would think that styling the first list item would be the same process considering it still has “friend” in it, but that’s not the case. Simply using =’friend’ won’t successfully target this anymore. Instead, we have to use the following, which looks for “friend” as one of the rel values.

li a[rel~='friend'] {font-weight: bold;}

This will result in the “Larry” list item being bolded where as the previous a[rel='friend'] syntax would’ve missed it.

CSS3 Attribute Selectors

CSS3 has given us so many cool new toys and tools to play with. It’s no surprise then that there are also some new Attribute Selectors that help us bring even more specificity into our targeting. Let’s start with my favorite.

Styling Similarly Named Attributes

This is where things get awesome. Let’s say you had the following HTML and that you wanted to target only the upperSection and lowerSection, how would you do it?

Lorem ipsum dolor sit amet...

Lorem ipsum dolor sit amet...

Lorem ipsum dolor sit amet...

One easy answer is the new “Arbitrary Substring Attribute Value Selector”, or “the really cool little asterisk thing.” Since the two divs that we want to target both contain “Section” in their names, we can easily target them.

div[id*='Section'] {color: red;}

I was blown away by this. Here we’re using CSS to actually dig through our ID names to find specific values within a larger name and target those elements. This opens up a lot of possibilities and makes complex targeting with little markup a much easier task.

Beginning and Ending

While the Arbitrary Substring Attribute Value Selector will target a given string anywhere, the Beginning and Ending versions allow rarer cases to be handled where you only want the first or last item to be considered.

Let’s say we want to target all the stooges, making Larry and Moe red and Curly yellow. To do this, we can insert use [title^='stooge'] to grab all those with “stooge” as the first word and [title$='stooge'] to grab all those with “stooge” as the last word.

li a[title^='stooge'] {color: red} /*Beginning*/
li a[title$='stooge'] {color: yellow} /*Ending*/

Chaining Attribute Selectors

Let’s say you want to get super specific and add on multiple criteria. That’s as simple as chaining together multiple attribute selectors. Let’s see how this works with the HTML below.

Now, let’s target any link with “stooge” in the title, but only those beginning with “the”. Notice that we don’t want to casually target “the” because this also appears in the last item. Here’s the syntax for achieving this:

li a[title*='stooge'][title^='the'] {color: red;}

Simple right? All we did was take the two rules that we needed and put them on the same line. It’s important to note that this isn’t an either/or scenario but a both/and. Only those items that meet both criteria will be changed.

Further Reading

If you’re enough of a nerd that you’re just loving attribute selectors, there are two more sources that I highly recommend that you check out.

CSS Tricks

First, Chris Coyier has a very thorough introduction over at CSS Tricks covering much of the same content that we covered here. Chris is a CSS super genius though and likely explains them much better than me!

The Book of CSS3

Next, check out Peter Gasston’s The Book of CSS3, which has been my main reference for all things CSS3 lately. I simply can’t get enough of this book and have given it quite the permanent position on my desk! Gasston adds to this conversation with a discussion of General and Adjacent Sibling Combinators, which are another interesting way to target certain elements. Take the following HTML as an example:

Not this one.

Gibberish

Pick me!

Lorem ipsum dolor sit amet...

Lorem ipsum dolor sit amet...

Lorem ipsum dolor sit amet...

Now, let’s say we wanted to target only the “Pick me!” paragraph. The Adjacent Sibling Combinator let’s us do just that. The following code targets any p tags immediately preceded by an h1 tag. There is only one of these in the example above (the first paragraph after the header).

h1 + p {color: orange;}

Similarly, the General Sibling Combinator will allow us to target all of the p tags that come after the header. So that first paragraph won’t change color, but all of the others will.

h1 ~ p {color: orange;}

This is just a taste, for more information on these, check out The Book of CSS3.

Browser Support

As I mentioned briefly above, as far as I can tell, you’re pretty covered on most of these techniques back to IE7 with all major current browsers rocking perfect support. However, it’s not exactly a full score across the board with some of the lesser-known browsers being a little spotty. You can find a nice little table of browsers and their support for all of this stuff and more at dev.l-c-n.com.

Conclusion

To be honest, I very recently knew little to nothing about CSS attribute selectors. After a little bit of research though I was stunned by how cool they are and baffled as to why they seem to be so rare (browser support is better than for a lot of the stuff we mess with). With just a little bit of code, you can achieve remarkably specific targeting with little to no additional markup required.

Leave a comment and let me know what you think of attribute selectors and whether or not you ever use them!

Comments & Discussion

20 Comments

  • http://www.jasonagross.com Jason Gross

    As usual, good stuff Josh. I am a big fan of using selectors because it can keep your HTML skinny and give you even more power with your CSS.

    I love the application Peter Gasston used in his book as a practical way to exercise the power of attribute selectors.

    A personal favorite of mine is using selectors to hit form elements by type or form labels by value to avoid a cluster of IDs.

  • http://www.billdawson.net Justin

    Good article. This is one of those topics I tend to forget about and over look since its used so rarely. In fact I haven’t even taken the time to look at what they added in CSS3 although I will after reading this.

  • Bart

    Nice article, though I would advise not to use the “rel” attribute to store user defined data. Since HTML5, we are allowed to use custom “data-*” attributes (always prefixed with “data-”).

    That way, the “friends” example should be written as:
    Moe

  • http://www.htmlartists.com/ HTML Artists

    Good stuff Josh. Big fan of using selectors because it can keep your HTML skinny and give you even more power with your CSS

  • http://webstandard.kulando.de Webstandard-Blog

    Helpful article Josh and thx for the tipp “The Book of CSS3″. I did’nt know it and you review of that book sounds good.

  • http://ioov.comule.com Will

    Amazing read!!! I never thought styling using attributes could be such a powerful tool in web design. A must use from now on.

  • Alex

    Good article! I think you could explain what the syntax means though… It’s a regular programming convention ( I believe or maybe just from JavaScript) I believe where ‘*=’ means ‘contains somewhere’ , and ‘^=’ means ‘starts with’ etc etc…

    Thanks for reminding me about these, very useful.

  • http://thebookofcss3.com/ Peter Gasston

    I’m really glad to hear you’re getting plenty of use out of my book, Joshua. Thanks for your review and kind words.

    I agree that selectors are quite overlooked, but you can do some cool stuff with them; I like this:

    E:nth-child(odd):not(:last-child) {}

  • http://totally-designed.be Joni

    Nice article! Will be using this more and more now!

  • http://www.iseevines.com Ivy

    Bookmark’d this article already. I can already see where I will be using this in the future. Thanks!

  • http://www.solarwin3d.nl Jasper van Es

    I love to use selectors. Especially when styling forms where most of the tags are Input tags. For example, if you want to style all checkboxes just say input[type="checkbox"].

  • http://andrew.peacock.us/ Andrew Peacock

    Great article, I’ll definitely be using this as a reference. I’ll need to try some of these out. I’m not sure if they’ll be able to replace my love for nth-child though…

  • http://www.ericbieller.com Eric Bieller

    Well said, though in many of the samples above, simply adding something like class=”friend” and styling it from .friend { } would suffice. I will say that these come in handy in some odd situations though. Nice to have functions like these available. Thanks for sharing

  • http://www.webdesigncreare.co.uk Kim Ruddock

    It’s always good to know about these extra ‘hooks’ on which styles can be hung. I do find myself creating many extra ids in order to style specific elements so hopefully some of these tips will help streamline my code. I would like to know is there any order of specificity for the new CSS3 selectors? How could I avoid clashes across supporting and non-supporting browsers?

  • http://www.daytonohiowebdesigners.com Jeffrey Friend

    This is good stuff! I can’t believe I knew so little about such a powerful css tool. It’s kinda like having an “Easy Button” for styling. Thanks so much!

  • http://Jim-Nielsen.com Jim

    Great article! Pretty simple stuff, I don’t know why these types of selectors arent used more often! Thanks a bunch!

  • http://www.united1in.com Vikram

    Thankyou very much for the information, it wil shorten CSS code and help me write more elegant code.

  • John S.

    Great article! But what is the general consensus about how to get all of this CSS goodness to play nice even in IE6? There seem to be a lot of shims/hacks out there, but I’m curious to know what people’s preferences are.

  • Jack

    with css evaluation right to left would this –
    li a[title*='stooge'][title^='the'] {color: red;}
    be better off swapped around?
    li a[title^='the'][title*='stooge'] {color: red;}

    as I assume finding ‘the’ starting a line would be way more common that having stooge in it.

    Great articles.

  • http://thewebdesigner43.blog.com cheap websites london

    It’s truly very complex in this active life to listen news on Television, therefore I only use the web for that reason, and take the hottest news.

Subscribe
Membership
About the Author