CSS Pseudo Classes

Sunday, July 05, 2009

CSS3 has been floating around out there for a while but it still hasn't gotten a foothold - which is unfortunate. One feature that will change the way you think about your CSS is support for massively more-powerful pseudo-classes. Currently we stylers are limited to :hover and in most cases :first-child & :last-childIf you regularly use jQuery or at least look through the docs you know that there are some other pretty powerful options that would make some of CSS sweater.

Now that Firefox 3.5 is finally out, designers and developers are getting closer than ever to having some of these pseudo-classes available. Here are some of the new options that Firefox 3.5 supports:

These two pseudo-classes allow you to select the first and last item in a list of siblings within a particular element. You can use this to color the first item in a list, use opacity to make the last paragraph on a page fade out or a number of other things.#type-ex1 div:first-of-type {
color: #C00;
}

:last-of-type

:only-of-type

only-of-type is similar to the previous two, but only selects an element if it has no siblings with the same name. .type-ex2 img:only-of-type { display: none; }

:nth-child

This pseudo-class lets you apply styles to groups of elements. The most common use case is to highlight odd or even items in a table:tr:nth-child(even){ background-color: #E8E8E8; } You can also use this to style just the 4th child element: tr:nth-child(4){ background-color: #CCFF00; } If you're feeling adventurous and you want to groups of 5 where the 2nd element in each group is styled then try this: tr:nth-child(5n+2){ background-color: #CCFF00; }

:nth-last-child

The :nth-last-child pseudo-class works exactly like the :nth-child pseudo-class except that it counts elements in the opposite direction.

:nth-of-type

The :nth-of-type pseudo-class uses the same kind of syntax as the other elements here but allows you to select based on element type. Use this if you want (for example) the 3rd paragraph tag regardless of how many other sibling tags there are.

:nth-last-of-type

The :nth-last-of-type pseudo-class works exactly like the :nth-last-of-type pseudo-class except that it counts elements in the opposite direction.

Awesome! Think of how much PHP (or insert your favorite server-side language here) you no longer need to worry about to handle things like zebra striping your tables or styling the bulleted lists. So what's the catch? You guessed it - IE is still playing catchup. Maybe IE11.