In CSS, is it possible to recursively select all :last-child from body?
Given this markup:
<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>
I am looking for div no. 3, 4 and 6
Another way to put it is this:
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 */
}
But obviously this is not a good approach.
When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.
The :not() selector excludes the element passed to it from selection. The :last-child selector selects the last child. Combining these two above selector to excludes the last children (inner-div) of every parent div from the selection.
No, unfortunately that's just about the only way to do it without modifying the HTML.
There has been at least one request for recursive versions of the :first-child
and :last-child
pseudo-classes, but it doesn't seem to have gained much favor. Notice it suggests nesting and repeating the pseudo-classes in the same way as in your question:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With