在CSS中,是否可以递归选择all: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 no。 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 */
}
但显然这不是一个好方法。
答案 0 :(得分:6)
不,不幸的是,这只是在不修改HTML的情况下实现它的唯一方法。
:first-child
和:last-child
伪类的递归版本有at least one request,但它似乎没有得到太多的帮助。请注意,它建议以与问题相同的方式嵌套和重复伪类:
目前,AFAIK,我们只能将儿童与预先知道的某些精确嵌套级别匹配(以下示例中为3):
.container > :first-child, .container > :first-child > :first-child, .container > :first-child > :first-child > :first-child {}
我们不能只使用:first-child上下文选择器,因为它也会选择不是第一个孩子的块的第一个孩子。
所以我们需要一种递归选择器,它不仅匹配最后一个子元素的第一个,而且递归匹配所有最前面和最后一个元素,而不管它们的嵌套级别如何。
答案 1 :(得分:1)
无需一直链接。就像这样
div:last-child {
/* Your GREAT css */
}
更新:在这种情况下,请为div2
提供一个典型的课程并使用:not()
推出选择
div:last-child:not(.nolist) {
border: 1px solid red;
}
答案 2 :(得分:0)
body :last-child {
color:red;
}
body :not(:last-child) :last-child {
color:initial;
}