You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

2022年是否可实现CSS向上选择同级元素?

Is there a "previous sibling" selector?

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 16:12:38