Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

first-child and nth-child selectors on HTML5 "article" tag not being applied

I'm using some CSS2 and CSS3 selectors on a HTML5 <article> tag, but it seems a few (but not all) of them aren't working as I'd expect.

Here's a runnable example:

/* Working as expected: */
div.wrapper p:first-child { color: red; }
div.wrapper p:nth-child(even) { color: fuchsia; }

/* NOT working as expected: */
div.wrapper article:nth-child(1) { color: blue; }
div.wrapper article:first-child { color: green; }

/* Working as expected: */
div.wrapper article:last-child { color: gold; }
<div class="wrapper">
  <p>P1, expected "color: red"</p>
  <p>P2, expected "color: fuchsia"</p>
  <p>P3, expected no css applied</p>
  <p>P4, expected "color: fuchsia"</p>
  <article>Article 1, expected "color: green" and/or "color: blue" &larr; not working as expected...</article>
  <article>Article 2, expected "color: gold"</article>
</div>

My problem then is: why won't the nth-child(n) and first-child selectors on <article> tags work? And even weirder: the last-child selector does work. I tested in FF4, IE9 and Chrome11, all the same results.

The <p> tags function as a a sanity check; to see that the nth-child(n) selector does work for some tags.

What am I missing? Is my sample supposed to work at all?

like image 607
Jeroen Avatar asked Jun 06 '11 18:06

Jeroen


2 Answers

first-child only selects the tag if it is the first child tag of its parent tag. In your case, the first <article> tag is the fifth tag overall. Same goes for nth-child(n). It is not related to sibling tags of the same type, but to all sibling tags. From W3C :

The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element.

Source: http://www.w3.org/TR/css3-selectors/#nth-child-pseudo

like image 110
Laurent Avatar answered Jun 18 '23 12:06

Laurent


The article element in your example is a 5th child not a first child. :first-child and nth-child(1) select the first child of the parent.

The :first-of-type (or :nth-of-type(1)) selector however will select the first element of type article.

like image 34
melhosseiny Avatar answered Jun 18 '23 11:06

melhosseiny