, but i...">

Selectors of the first and third children in the HTML tag "article" are not applied

I use the CSS2 and CSS3 selector in the HTML5 <article> , but it seems that some (but not all) of them do not work as I expected.

Here is an 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 is this: why the nth-child(n) and first-child selectors on <article> tags do not work? And even stranger: last-child selector works. I tested in FF4, IE9 and Chrome11 all the same results.

The <p> tags function as a health check; that the nth-child(n) selector works for some tags.

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

+6
source share
2 answers

first-child selects only the tag if it is the first child tag of its parent tag. In your case, the first <article> tag is the fifth tag as a whole. The same goes for nth-child(n) . This does not apply to twin tags of the same type, but to all sibling tags. From W3C:

The nth-child (a + b) pseudo-class designation is an element in which there are siblings + b-1 in front of it in the document tree, for any positive integer or zero value n and has a parent element.

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

+13
source

The article element in your example is the fifth child, not the 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 .

+6
source

Source: https://habr.com/ru/post/889892/


All Articles