Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 927
Ben Avatar asked Dec 28 '22 04:12

Ben


2 Answers

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/

like image 105
Rob W Avatar answered Dec 31 '22 04:12

Rob W


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

like image 20
rjz Avatar answered Dec 31 '22 04:12

rjz