Ben
Ben

Reputation: 764

Why does the :nth-child(2) selector work on what I expect to be :first-child?

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

Answers (3)

w3uiguru
w3uiguru

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

rjz
rjz

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.

Fiddle here

Upvotes: 3

Rob W
Rob W

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.

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

Upvotes: 6

Related Questions