Reputation: 764
I have an example of what I'm trying to ask.
I use this kind of format often. I'd expect to be able to select that first div with fieldset div:first-child { }
but it seems that it's only grabbed by the 2nd child selector. I would expect "field 1" to be red and not blue. It makes more sense semantically (to me at least) to say "style the first div in the fieldset like so" instead of saying the 2nd.
Why is this happening and is there a way to achieve the effect I want (to be able to call div:first-child)?
Upvotes: 4
Views: 4405
Reputation: 5895
Here is the explanation how :nth-child selector works:
This pseudo-class matches elements on the basis of their positions within a parent element’s list of child elements. The pseudo-class accepts an argument, N, which can be a keyword, a number, or a number expression of the form an+b. For more information, see Understanding :nth-child Pseudo-class Expressions.
If N is a number or a number expression, :nth-child(N) matches elements that are preceded by N-1 siblings in the document tree.
The following example selectors are equivalent, and will match odd-numbered table rows:
tr:nth-child(2n+1) { ⋮ declarations } tr:nth-child(odd) { ⋮ declarations }
This example selector will match the first three rows of any table:
tr:nth-child(-n+3) { ⋮ declarations }
This example selector will match any paragraph that’s the first child element of its parent element:
p:nth-child(1) { ⋮ declarations }
This is, of course, equivalent to the selector
p:first-child.
Note: For more details on selector please see the link: http://reference.sitepoint.com/css/pseudoclass-nthchild
Upvotes: 2
Reputation: 16510
In this case, the <legend>
preceding the first div is the actual :first-child
of their shared parent. You could consider using the :nth-of-type
selector.
Upvotes: 3
Reputation: 348972
The :nth-child
selector ignores the elements type. div:nth-child(2)
selects a <div>
which is a second child.
If you want to select the first div, use the :nth-of-type(1)
or :first-of-type
selector.
Upvotes: 6