我们说我有一些HTML设置如下:
<div class="older-sibling">
<div class="first-child">
<div class="first-grandchild"></div>
</div>
<div class="second-child">
<div class="second-grandchild"></div>
</div>
<div class="third-child">
<div class="third-grandchild"></div>
</div>
</div>
<div class="younger-sibling"></div>
divs .first-child和.third-child将永远存在。然而,div .second-child可能不是。当.older-sibling的.second-child div不存在时,我可以通过检查它的父节点是否是.first-child的相邻兄弟来定位.third-grandchild div的css规则,就像这样:
.first-child + .third-child > .third-grandchild {
rule: foo;
}
在.second-child不存在的情况下,我还想应用一些针对.younger-sibling div的条件css。如何使用CSS实现这一点,而无需合并jQuery?
答案 0 :(得分:0)
如果您将younger-sibling
移到older-sibling
div中,您就可以使用纯CSS进行匹配。当第二个孩子不存在时,下面的CSS选择器应该匹配(尽管从技术上讲它不再是兄弟姐妹):
.older-sibling div:nth-child(3).younger-sibling { background: red; }
&#13;
<div class="older-sibling">
<div class="first-child">
<div class="first-grandchild">First child</div>
</div>
<!-- second child is missing -->
<div class="third-child">
<div class="third-grandchild">Third child</div>
</div>
<div class="younger-sibling">Younger</div>
</div>
&#13;
仅当third-child
是其父级的第二个子级时才会匹配,只有当second-child
不存在时才会发生。