Sass/CSS选择器编写:匹配含.ct_ver1且路径无.ct_ver2的元素
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.footerelement that's a descendant of.ct_ver1(regardless of how many containers are in between).:not(:has(ancestor .ct_ver2)): Excludes any.footerthat has any ancestor element (at any level) with the.ct_ver2class. This covers all cases where.ct_ver2exists in the DOM path above.footer, even if it's not a direct parent.
Verification against your rules:
- No specified class: If
.footerisn't inside.ct_ver1, the selector doesn't match, so no styles are applied ✔️ - Only inside
.ct_ver1: The selector matches, styles are applied ✔️ - Both
.ct_ver1and.ct_ver2in 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

