Bug in CSS

I’m learning about pseudo-class and I think I found a bug of :nth-of-type. I have 1 div has class 'container ’ and 6 div inside have class ‘item’. This is my code :

And when I run, everything is normal. The item 2 has ‘‘background-color : blue’’
But when I add an empty div element in front of item 1 . Like this :

Now when I run, item 1 has ‘‘background- color : blue’’. It’s different from the normal behavior of nth-of-type. It should be the item 2 has background blue. When I convert the empty div tag to a empty p tag . It works normally.

May it is a bug ?

Hi @Noname123 and welcome to the community :wave:

This works as expected. If you use a class together with this pseudo selector, you have to look at them separately. In your second screenshot with the empty <div> it selects the second <div> if it has the class “item” (Not the second with the class). Since now the second <div> is the one with number “1” and it has the class, it gets selected.

Does that make it clearer?

Michael

Thank you @mikoMK
I understood this problem. But in screenshot 2, if I want to choose the second element of ‘item’ class - in this situation ,it is <div class='item'> 2 </div>, how could I code ?

1 Like

You’re looking for something like :nth-of-class(), but unfortunately this doesn’t exist. So you have to find another solution.

I don’t know your exact situation, but if you are dynamically changing the HTML structure and applying classes and can’t use :nth-child() or :nth-of-type(), then you could as well dynamically set an additional class on the element you want to target. Something like <div class="item special"> and then use .item.special {} to apply CSS.