skip to Main Content

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


  1. 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.

    .wrapper .item:has(.inner-element.type-b) {
      border: 1px solid red
    }
    
    .wrapper .item:has(.inner-element.type-b) ~ .item:has(.inner-element.type-b) {
      border: unset
    }
    
    Login or Signup to reply.
  2. You can use:

    .item:nth-child(1 of :has(.inner-element.type-b)) {
      border:1px solid red;
    }
    
    
    [class]:before {
      content:attr(class);
    }
    <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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search