假设我有以下HTML结构:
<div>
<div class="class1">
<p class="subclass">whatever</p>
</div>
<div class="class2">
<p class="subclass">whatever</p>
</div>
<div class="class3">
<p class="subclass">whatever</p>
</div>
</div>
是否可以使用一个CSS选择器规则来定位具有类名subclass
或class1
的祖先下的类名class2
的元素?
答案 0 :(得分:3)
您可以使用:not()
的属性选择器选择以.class*
开头并排除.class3
[class^="class"]:not(.class3) .subclass {
color: red;
}
<div>
<div class="class1">
<p class="subclass">whatever</p>
</div>
<div class="class2">
<p class="subclass">whatever</p>
</div>
<div class="class3">
<p class="subclass">whatever</p>
</div>
</div>
您可以随时组合选择器
.class1 .subclass, .class2 .subclass {
color: red;
}
<div>
<div class="class1">
<p class="subclass">whatever</p>
</div>
<div class="class2">
<p class="subclass">whatever</p>
</div>
<div class="class3">
<p class="subclass">whatever</p>
</div>
</div>