rhavin
rhavin

Reputation: 1689

Why is this css sibling selector not selecting all the siblings?

  li:has(>label) {
    background: #0c0;
  }
  li~li:has(>label) {
    border: 4px solid #c0c;
  }
  
  
<ul tabindex="-1">
<li><input type="radio"/ name="r6a" id="r61a" value="6.0a" /><label for="r60a">[Item 6.0]</label></li>
<li tabindex="0">[Item 6.1]</li>
<li><input type="radio"/ name="r6a" id="r62a" value="6.2a" /><label for="r62a">[Item 6.2]</label></li>
<li><input type="radio"/ name="r6a" id="r63a" value="6.3a" /><label for="r63a">[Item 6.3]</label></li>
<li tabindex="0">[Item 6.4]</li>
</ul>

As I read this, the first selector is selecting lis that have a label as direct descender and the second is selecting all lis that are siblings to a li that has a label. But why is the last selector just selecting items 6.2 and 6.3? It should either select all of them (inclusively all are siblings to a li that has a label) or it should select 6.1 and 6.4 (if it is exclusive).

According to this: https://developer.mozilla.org/en-US/docs/Web/CSS/Subsequent-sibling_combinator

They dont have to be next to each other, just share the same parent. Which they do.

Upvotes: 0

Views: 52

Answers (1)

A Haworth
A Haworth

Reputation: 36426

The requirement is to :

select all lis that have the same parent as a li that has a label as direct descentant

So you want all the lis in a ul to be selected if any one of them has a label as a direct descendant.

You can use :has on the ul (ie the parent) for this:

  ul:has(>li>label) > li { 
    border: 4px solid #c0c;
  }
  
  
<ul tabindex="-1">
<li><input type="radio"/ name="r6a" id="r61a" value="6.0a" /><label for="r60a">[Item 6.0]</label></li>
<li tabindex="0">[Item 6.1]</li>
<li><input type="radio"/ name="r6a" id="r62a" value="6.2a" /><label for="r62a">[Item 6.2]</label></li>
<li><input type="radio"/ name="r6a" id="r63a" value="6.3a" /><label for="r63a">[Item 6.3]</label></li>
<li tabindex="0">[Item 6.4]</li>
</ul>

Upvotes: 2

Related Questions