有条件地应用基于紧邻兄弟姐妹的css规则

时间:2015-07-28 01:50:14

标签: html css css-selectors

我们说我有一些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?

1 个答案:

答案 0 :(得分:0)

如果您将younger-sibling移到older-sibling div中,您就可以使用纯CSS进行匹配。当第二个孩子不存在时,下面的CSS选择器应该匹配(尽管从技术上讲它不再是兄弟姐妹):

&#13;
&#13;
.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;
&#13;
&#13;

仅当third-child是其父级的第二个子级时才会匹配,只有当second-child不存在时才会发生。