So, you're pretty good at CSS... you know some selectors... you're feeling pretty confident... therefore I challenge you!

Question -> Given the following snippet of HTML:

<div>
  <h1>heading</h1>
  <p>Some text...</p>
  <p>More text...</p>
</div>

What does div p:first-child select, eh?

Answer -> Nothing!

Confused? So was I...

The confusion stems from what you think :first-child is applied to. Using parentheses to explain operator precedence, you were probably thinking of:

(div p):first-child

when the :first-child selector is applied to the result of (div p).

The problem is, there is NO such notion of parentheses in the CSS specification, and operator precedence is strictly left to right. So in actuality, the selector is:

(div) (p:first-child)

That is, it is looking for a div whose :first-child is a p - which doesn't exist in the snippet of HTML.

What you need is the CSS3 :first-of-type selector:

div p:first-of-type

And how did I notice this?

I was adding extra :last-child and :nth-child(xxx) pseudo classes to Sizzle and started to doubt the rules I had written for :first-child.

By the way, I've got it all sorted now!

Have fun!

:)


Discuss