CSS-选择一个包含子类的类

时间:2019-02-26 00:40:48

标签: css

我有一个父类.parent-class,并且仅在该类具有名为child-class的子类的情况下,才想对其应用某种样式。我是这样做的,但是没用:

.parent-class:has(.child-class){
  background: red;  
}

1 个答案:

答案 0 :(得分:2)

据我所知,无法使用CSS做到这一点。

我建议使用jQuery :has(),如下所示。

$(".box1:has(.box2)").addClass("box3");
.box1 {
  width: 100px;
  height: 100px;
  background-color: red;
}

.box3 {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box1">
  <div class="box2"></div>
</div>

<div class="box1"></div>