Is it possible to sibling upwards in 2022?

Viewed 103

Referring to this Stackover question from 2009 (Is there a "previous sibling" selector?), it seems that it was not possible then.

Here are two small examples that illustrate the problem

  1. both elements touched by the CSS are under the triggering element.
  2. In example two one Element is above the triggering element and the other remains below it. As a result, the sibling selector does not affect the element on top.

Example one

.toggle-switch {
  padding:50px;
}
#nocheck {
  margin-bottom: 2px;
} 

#chkTest:checked ~ #check { color: green; }
#chkTest:checked ~ #nocheck { color: black; }
#check { color: black; }
#nocheck { color: blue; }
  <div class="">
    <div class="toggle-switch">
      
      <input type="checkbox" id="chkTest" name="chkTest">
      <label for="chkTest">
        <span class="toggle-track"></span>
      </label>
      <div class="" id="nocheck">ENABLE</div>
      <div class="col-3 col-md-3" id="check">DISABLE</div>
      
    </div>
  </div>

Example 2

.toggle-switch {
  padding:50px;
}
#nocheck {
  margin-bottom: 2px;
} 

#chkTest:checked ~ #check { color: green; }
#chkTest:checked ~ #nocheck { color: black; }
#check { color: black; }
#nocheck { color: blue; }
  <div class="">
    <div class="toggle-switch">
      <div class="" id="nocheck">ENABLE</div>
      <input type="checkbox" id="chkTest" name="chkTest">
      <label for="chkTest">
        <span class="toggle-track"></span>
      </label>
      
      <div class="col-3 col-md-3" id="check">DISABLE</div>
      
    </div>
  </div>

1 Answers

It's the same issue as with a parent selector, CSS can only see DOWN the DOM not back up. As in it can only see future siblings, children, children of children etc.

Safari I think has implemented the :has() pseudo class in one of their dev versions but they are a small browser and Chrome has yet to implement anything.

You might get duped as a few questions on here, this is probably a useful one: Is there a CSS parent selector?

Kevin Powell has a great video https://www.youtube.com/watch?v=2-xdcDsqsAs

Related