2022年是否可实现CSS向上选择同级元素?
Back in 2009, pure CSS had no way to select a previous sibling element—meaning you couldn't target an element that sits before another element in the same parent container using native selectors. This was a common pain point, and we can see why with two practical examples:
Example 1: Targeting elements after the trigger works
In this scenario, both elements we want to style come after our checkbox trigger. The general sibling combinator (~) functions exactly as intended here.
CSS
.toggle-switch { padding:50px; } #nocheck { margin-bottom: 2px; } #chkTest:checked ~ #check { color: green; } #chkTest:checked ~ #nocheck { color: black; } #check { color: black; } #nocheck { color: blue; }
HTML
<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>
When you check the box, both #nocheck and #check update their colors correctly—since they're siblings positioned after the trigger checkbox.
Example 2: Targeting an element before the trigger fails
Here, we moved #nocheck to sit before the checkbox trigger. Even with the exact same CSS, the sibling combinator can't reach the element that precedes the trigger.
CSS
.toggle-switch { padding:50px; } #nocheck { margin-bottom: 2px; } #chkTest:checked ~ #check { color: green; } #chkTest:checked ~ #nocheck { color: black; } #check { color: black; } #nocheck { color: blue; }
HTML
<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>
When you check the box, only #check (which comes after the checkbox) turns green. #nocheck stays blue because the ~ selector only targets siblings that come after the referenced element—there was no native way to "look back" to earlier siblings in 2009.
内容的提问来源于stack exchange,提问作者Maik Lowrey

