使用一个CSS选择器规则定位多个类的子项

时间:2017-03-10 02:11:31

标签: html css

假设我有以下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选择器规则来定位具有类名subclassclass1的祖先下的类名class2的元素?

1 个答案:

答案 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>