【问题标题】:Conditionally apply a css rule based on immediately adjacent sibling's children根据直接相邻的兄弟姐妹的孩子有条件地应用 css 规则
【发布时间】:2015-07-28 12:09:09
【问题描述】:

假设我有一些这样的 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>

div .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?

【问题讨论】:

  • .second-child 怎么会缺席?它是在加载时存在,还是从未存在但将来会存在?
  • 这样的事情你不必使用jQuery,你可以很好地使用原生JS,但更好的问题是:为什么只使用css?
  • 我想用 CSS 而不是 JS 来减少开销。 .second-child 在加载时不存在,但我希望它的行为方式相同,即使使用开发人员工具手动删除该元素(另一个纯粹在 CSS 中执行此操作的原因)。
  • 你不能用 CSS 来做这件事,因为一旦你确定 second-child 不存在,就没有办法遍历备份 DOM。你需要 JavaScript。
  • Is there a CSS parent selector? 的可能重复项

标签: html css css-selectors


【解决方案1】:

如果将younger-sibling 移动到older-sibling div 中,则可以使用纯CSS 匹配它。当第二个孩子不存在时,以下 CSS 选择器应该匹配(尽管从技术上讲,它不再是同级):

.older-sibling div:nth-child(3).younger-sibling { background: red; }
<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>

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

【讨论】:

    猜你喜欢
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 2020-07-28
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多