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 :
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.
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.
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 ?
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.