css - 选择递归 :last-child. 可能吗?

标签 css css-selectors

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

鉴于此标记:

<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 */
}

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

最佳答案

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

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

Currently, AFAIK, we can only match children up to some exact nesting level known in advance (3 in the example below):

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

We cannot use just :first-child context selector since it would also select first children of blocks that are not first children themselves.

So we need a sort of recursive selector that matches not just first of last child, but recursively matches all first-most and last-most elements regardless of their nesting level.

关于css - 选择递归 :last-child. 可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12477272/

上一篇:css - 多个伪元素

下一篇:css - 透明头痛

相关文章:

html - 如何使 Bootstrap 导航栏移动友好?

html - CSS - 首字母选择不适用于 ID

css - 如何使用 nth-of-type 来选择嵌套的 child

javascript - 在 jQuery 的 if 条件中使用 AND 运算符

css - 选择器无法正常工作

javascript - 如何检查 head 中是否包含 css/js 资源

javascript 工具提示跟随光标位置

python - 如何通过 Selenium 和 Python 单击跨度类文本

html - HTML 中的超链接::之后

css - 没有 CSS 样式的新菜单链接