Anne van Kesteren

Structural pseudo-classes

With the new CSS3 selectors module CSS is finally getting somewhere I think. I'm not going to cover all in this little piece of writing, but only (as the title says) Structural pseudo-classes [6.6.5]. It looks like just a tiny bit of the spec (and it is actually), but I think this is the most interesting part of CSS3 selectors and therefore good to start with.

These new selectors are especially nice for lists and tables. I think everyone knows a PHP BB forum where the odd rows have a different background color if you compare them to the even rows. I think they have done it with CSS classes now. I agree with the use of class, using the adjacent sibling selectors would be very (very!) difficult (apart from that this selectors is not supported by IE).

Structural pseudo-classes starts with the :root pseudo-class. This is really nice if you want to select the root element. Off course in XHTML this pseudo-class isn't really necessary, but in XML it's more than welcome. After that the :nth-child() pseudo-class is introduced, which is quite powerful. If you use this rule: :nth-child(3n+3) it matches every third (child) element (starting from 3). The :nth-child() pseudo-class can also take the values odd an even, which are going to be used the most on forums imo.

The :nth-last-child() pseudo-class is exactly the same as the :nth-child() pseudo class, with the only exception that this counts from the last child, obvious isn't it? Everything said before does also count for the :nth-of-type() pseudo-class and the :nth-last-of-type() pseudo-class, with the exceptions that these do not apply on the children of the selector, but on the selector itself.

Than a quick check to the last structural pseudo-classes:

Content pseudo-class [6.6.6], this one looks so good, I couldn't resist to tell you. Besides that, it gives a very good description what the difference is between a pseudo-class and a pseudo-element. Example of the selector:

p:contains("nothing"){
 background:green; /* yeah, I know which color looks good! */
}

So if a element p contains the substring "nothing" the whole element gets a green background color. Why the whole element?:

Note: :contains() is a pseudo-class, not a pseudo-element. The following CSS rule applied to the HTML fragment above will not add a red background only to the word "Markup" but will add such a background to the whole paragraph.

P:contains("Markup") { background-color : red }