Why is the nth-child (2) selector working on what I expect: the first child?

I have an example of what I'm trying to ask.

I often use this format. I expect that I can select this first div with the fieldset div:first-child { } , but it seems that it is only caught by the second selector. I would expect field 1 to be red, not blue. It matters more semantically (at least for me) to say โ€œstyle of the first div in a set of fields like thisโ€, instead of saying 2nd.

Why is this happening and is there a way to achieve the effect I want (to be able to call div: first-child)?

+4
source share
3 answers

The :nth-child selector ignores the type of elements. div:nth-child(2) selects a <div> , which is the second child.

If you want to select the first div, use the :nth-of-type(1) or :first-of-type selector.

Demo: http://jsfiddle.net/Z3Bcq/1/

+6
source

In this case, the <legend> preceding the first div is actual :first-child their common parent. You can use the selector :nth-of-type .

Spell here

+2
source

Here is an explanation of how the nth-child selector works:

This pseudo-class matches elements based on their positions in the list of parent elements of child elements. The pseudo-class takes an argument N, which can be a keyword, number or numeric expression of the form a + b. For more information, see Understanding: nth-child pseudo-class expressions.

If N is a numeric or numeric expression: nth-child (N) matches elements preceded by N-1 siblings in the document tree.

The following example selectors are equivalent and will correspond to lines of strings with odd numbers:

 tr:nth-child(2n+1) { โ‹ฎ declarations } tr:nth-child(odd) { โ‹ฎ declarations } 

This sample selector will match the first three rows of any table:

 tr:nth-child(-n+3) { โ‹ฎ declarations } 

This sample selector will match any paragraph that is the first child of its parent:

 p:nth-child(1) { โ‹ฎ declarations } 

This, of course, is equivalent to the p:first-child. selector p:first-child.

Note. For more information on the selector, see the link: http://reference.sitepoint.com/css/pseudoclass-nthchild

+2
source

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


All Articles