Friday, February 6, 2009

CSS: multiple class selection

I don't know how many times I've wished that I could select an HTML element that has two classes. I want to select the table rows that are both 'odd' and 'awesome'. So instead of doing this:

...
<tr class="even awesome">...</tr>
<tr class="odd awesome">...</tr>
...

I end up doing this:

...
<tr class="even awesome even_awesome">...</tr>
<tr class="odd awesome odd_awesome">...</tr>
...

I always felt dirty doing something like that, and thought there had to be a better way to do it. Well there is! It turns out that '.odd.awesome' will select those elements with both the 'odd' and 'awesome' classes.

This stylesheet:

.odd_awesome {
  color: red;
  size: 48pt;
}

Has now become:

.odd.awesome {
  color: red;
  size: 48pt;
}

And the HTML is simply:

...
<tr class="even awesome">...</tr>
<tr class="odd awesome">...</tr>
...

Now that I know this secret, I vaguely remember having known it many years ago (like when I was first introduced to CSS), but somehow I had forgotten it. It's like running into an old friend. "Hello Mr. CSS Selector! It's been a long time."

Now go simplify your HTML/CSS!

2 comments:

Lothar Hillperson said...

This CSS trick is neat, but is not cross-browser compliant. While modern browsers (e.g. Firefox 3, Safari, Chrome) support this style of selectors, IE6 does not.

I'd love to ignore this and use selectors like this, but unfortunately lots of people still use IE6.

paul said...

I didn't realize that IE6 doesn't support this selector.

Your choice is your own (and you may not have a choice). There may be good reasons to support IE6, but there are plenty of good reasons to ignore IE6.

http://idroppedie6.com/

http://productblog.37signals.com/products/2008/07/basecamp-phasin.html

http://superfluousbanter.org/archives/2008/09/the-final-word-on-ie6/