Dalibor Slavík
Dalibor Slavík

Reputation: 61

nth-child doesn't work when the tag SPAN is on

Here is my code

<span></span>
<div class='box'>title</div>
<style>div.box:nth-child(1) { color: red; }</style>

It works when I delete the span tag or any other tag which is over the box, but not when I leave it as is. Why is it so?

Upvotes: 0

Views: 166

Answers (2)

user2625787
user2625787

Reputation:

Because the div is now the second child. Use :nth-of-type(n) instead.

 <style>
  div.box:nth-of-type(1) { color: red; }
 </style>

That will select the first div

Upvotes: 2

user1281428
user1281428

Reputation:

Use :nth-of-type .

Basically :nth-child counts ALL the siblings. Regardless of type of element. However :nth-of-type takes into account the element selected.

Upvotes: 5

Related Questions