The nth-child
pseudo-class refers to the “Nth matched child element”, meaning if you have a structure as follows:
<div>
<h1>Hello</h1>
<p>Paragraph</p>
<p>Target</p>
</div>
Then p:nth-child(2)
will select the second child which is also a p (namely, the p
with “Paragraph”).
p:nth-of-type
will select the second matched p
element, (namely, our Target p
).
Here’s a great article on the subject by Chris Coyier @ CSS-Tricks.com
The reason yours breaks is because type refers to the type of element (namely, div
), but the first div doesn’t match the rules you mentioned (.row .label
), therefore the rule doesn’t apply.
The reason is, CSS is parsed right to left, which means the the browser first looks on the :nth-of-type(1)
, determines it searches for an element of type div
, which is also the first of its type, that matches the .row
element, and the first, .icon
element. Then it reads that the element should have the .label
class, which matches nothing of the above.
If you want to select the first label element, you’ll either need to wrap all of the labels in their own container, or simply use nth-of-type(3)
(assuming there will always be 2 icons).
Another option, would (sadly) be to use… wait for it… jQuery:
$(function () {
$('.row .label:first')
.css({
backgroundColor:"blue"
});
});