【问题标题】:Select recursive :last-child. Possible?选择递归 :last-child。可能的?
【发布时间】:2020-09-15 21:26:57
【问题描述】:

在 CSS 中,是否可以递归选择所有 :last-child from body?

鉴于此标记:

<body>
  <div id="_1">
    <div id="_2"></div>
  </div>
  <div id="_3">
    <div id="_4">
      <div id="_5"></div>
      <div id="_6"></div>
    </div>
  </div>
</body>

我正在寻找 div 号。 3、4、6

另一种说法是:

body > :last-child,
body > :last-child > :last-child,
body > :last-child > :last-child > :last-child,
body > :last-child > :last-child > :last-child > :last-child {
  /* My stuff here */
}

但显然这不是一个好方法。

【问题讨论】:

标签: css css-selectors


【解决方案1】:

不,不幸的是,这只是不修改 HTML 的唯一方法。

at least one request 用于 :first-child:last-child 伪类的递归版本,但它似乎并没有获得太多青睐。请注意,它建议以与您的问题相同的方式嵌套和重复伪类:

目前,AFAIK,我们只能将子级匹配到预先知道的某个 exact 嵌套级别(下例中为 3):

.container > :first-child,
.container > :first-child > :first-child,
.container > :first-child > :first-child > :first-child {}

我们不能只使用 :first-child 上下文选择器,因为它还会选择块本身不是第一个孩子的第一个孩子。

所以我们需要一种 recursive 选择器,它不仅匹配最后一个子元素的第一个,而且递归地匹配所有第一个和最后一个元素,无论它们的嵌套级别如何。

【讨论】:

  • 好吧,我害怕那个。谢谢。
【解决方案2】:
body :last-child {
    color:red;
}
body :not(:last-child) :last-child {
    color:initial;
}

任何不是最后一个子元素的后代的最后一个子元素都将反转更改。

【讨论】:

  • 任何作为非最后一个子元素的后代的最后一个子元素都将反转更改。
  • 将此添加到答案中
  • 这很诱人。但是您必须对未选择的元素使用 color:initial; 感到满意,否则您必须使用更具体的选择器来解决它。
【解决方案3】:

不用一路上链。就这么简单

div:last-child {
   /* Your GREAT css */
}

Demo

更新:在这种情况下,给div2 一个典型的类并使用:not() 推出选择

div:last-child:not(.nolist) {
    border: 1px solid red;
}

Demo

【讨论】:

  • 这也将选择 div 编号。 2.
  • @LasseDahlEbert,误解了这个问题。它实际上非常简单。查看更新和演示 :)
  • 感谢您的回答,但这不是我要找的。看这个分叉的演示:jsfiddle.net/HHKc7 - 我不想要 div 2
  • 嗨 Starx - 感谢您的努力,但我正在寻找一种非常通用的方式来选择“:last-child”的路径。如果我有一个具体的案例,我会按照你的建议来摆脱困境。
猜你喜欢
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-31
  • 2013-04-30
相关资源
最近更新 更多