I’m looking for a way to select the first, and only the first, parent element which contains another element with a given class within it.
So for example:
<div class="wrapper">
<div class="item">
<div class="inner-element type-a">
</div>
</div>
<div class="item">
<!-- want to select this one -->
<div class="inner-element type-b">
</div>
</div>
<div class="item">
<div class="inner-element type-b">
<!-- but not this one -->
</div>
</div>
</div>
So I can use .wrapper .item:has(.inner-element.type-b)
to select all of the item
divs which contain an element with the type-b
class but I only want to target the first one.
I tried .wrapper .item:has(.inner-element.type-b):first-of-type
but that didn’t seem to target the element correctly. Is this even possible with CSS alone or is my combination of selectors the issue?
2
Answers
A possible option is to apply your first rule then "unapply" it to subsequent elements you don’t wish to style with the adjacent sibling selector
~
e.g.You can use: