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

Sass/CSS选择器编写:匹配含.ct_ver1且路径无.ct_ver2的元素

Solution for Your Sass/CSS Selector Issue

Let's break down why your original selector wasn't working first: your code only checks if the direct parent div of .footer isn't .ct_ver2, but it doesn't account for .ct_ver2 existing anywhere else in the ancestor chain (like in a higher-level container such as ct_ver1_container). That's why the style was still applying even when .ct_ver2 was present elsewhere.

Here's the correct selector that meets all your requirements:

.ct_ver1 .footer:not(:has(ancestor .ct_ver2)) {
  float: left;
  position: relative;
  width: 100%;
  overflow: hidden;
}

How this works:

  • .ct_ver1 .footer: Targets any .footer element that's a descendant of .ct_ver1 (regardless of how many containers are in between).
  • :not(:has(ancestor .ct_ver2)): Excludes any .footer that has any ancestor element (at any level) with the .ct_ver2 class. This covers all cases where .ct_ver2 exists in the DOM path above .footer, even if it's not a direct parent.

Verification against your rules:

  1. No specified class: If .footer isn't inside .ct_ver1, the selector doesn't match, so no styles are applied ✔️
  2. Only inside .ct_ver1: The selector matches, styles are applied ✔️
  3. Both .ct_ver1 and .ct_ver2 in path: The :not(:has(...)) clause excludes the element, so no styles are applied ✔️

Note on browser compatibility:

The :has() pseudo-class is supported in all modern browsers (Chrome, Firefox, Edge, Safari 15.4+). If you need to support older browsers, you'd have to use JavaScript to add/remove a custom class to .footer based on the presence of .ct_ver2 in its ancestor chain, but the above selector is the cleanest native CSS solution available today.

内容的提问来源于stack exchange,提问作者Sergej

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:59:21