I am sure this is possible but I’m not sure how to achieve it through CSS.
I want to target the 3rd instance of a class the first time the group is found and the 2nd instance the 2nd time it is found.
Here’s an over-simplified example of what I am working with:
<div class="foo">
<div class="bar">Non Target</div>
<div class="bar">Non Target</div>
<div class="bar">TARGET</div>
<div class="bar">Non Target</div>
</div>
<div class="foo">
<div class="bar">Non Target</div>
<div class="bar">TARGET</div>
</div>
Can this be achieved?
N.B. I am trying to achieve this without having to edit the HTML, CSS only
I have tried various combinations of nth-of-type etc but am not experienced enough to figure it out!
3
Answers
I found out how to do it.
Here is one possible solution.
nth-of-type
could also be replaced bynth-child
, but in both cases it depends whether there are other sibling elements (with no or different classes) on the same level, in which case both wouldn’t work the same way anymore.(
nth-of-type
only works if the element is the nth element of any type inside its parent and has the specified type and class)In addition to Johannes solution, we can further target somewhat more accurately using
nth-child(n of x)
in case there are intervening elements.