CSS3: the nth-child pseudo-class

The CSS3 nth-child pseudo-class is a powerful CSS3 selector that solves many problems encountered by web developers while trying to stylize certain elements based on their position in the DOM tree. As its name says, this pseudo-class selects an element if this element is the nth-child of its parent. This kind of selector accepts four types of values:

  1. the keyword even (for even elements)
  2. the keyword odd (for odd elements)
  3. the n index, starting from 1
  4. the an+b formula, where n is a literal constant and a and b are numbers.

Some examples:

tr:nth-child(odd) {
  background: #eee;
}

The above code selects all tr elements that are odd. But we can also selects other indexes, like so:

tr:nth-child(4) {
   background: #eee;
}

This code selects the 4th tr element. If we want to perform a repeated selection, for example by selecting all tr elements that are multiples of 3, we can write this formula:

tr:nth-child(2n+1) {
  background: #eee;
}

CSS3: The :not (negation) pseudo-class

What is, in its essence, the CSS3 :not pseudo-class? It's a filter that is used to separate certain elements from others depending on the presence of a certain condition. In technical terms, this pseudo-class uses a Boolean expression that negates a given condition. In human terms, it tells the browser not to consider an element with a given condition. For example:

p:not([class]) {
    color: green;
}

We're telling the browser to match each p element which has not a class attribute set on it. Very simple. Another example:

a:not(:link) {
  text-decoration: none;
}

In this case, we're matching an a element which is not a link (e.g. an anchor). As you can see, this pseudo-class negates the given condition. More information at http://www.w3.org/TR/css3-selectors/#negation.

CSS 3 selectors in Internet Explorer 9

A couple of days ago, Internet Explorer developers have announced that IE 9 will now support all the CSS 3 selectors. That includes also a pseudo-class like :selection:

However, we have to wait until the final release of IE 9 will be shipped to see if their implementation is correct. In fact, claiming that IE 9 passes all the tests of css3.info doesn't necessarily mean that it's bug-free. In the meantime, stay tuned with the CSS Test Suite to get the latest test cases from Microsoft.. but wait, they actually provided no tests on CSS 3 selectors! See http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/ for more details.