Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select recursive :last-child. Possible?

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.

like image 905
Lasse Skindstad Ebert Avatar asked Sep 18 '12 12:09

Lasse Skindstad Ebert


People also ask

How do you select all the elements except the last child?

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.

How do I not select the last child in CSS?

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.


1 Answers

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.

like image 76
BoltClock Avatar answered Oct 16 '22 00:10

BoltClock