Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting last consecutive sibling

How do I select the last element in a sequence of adjacent elements?

Consider the following markup:

HTML

<ul>
    <li class="foo">...</li>
    <li class="foo">...</li>
    <li class="foo">...</li> <!-- bingo -->

    <li class="bar">...</li>
    <li class="bar">...</li>
    <li class="bar">...</li>
    <li class="bar">...</li> <!-- bingo -->

    <li class="foo">...</li> <!-- bingo -->

    <li class="bar">...</li>
    <li class="bar">...</li> <!-- bingo -->
</ul>

The number of consecutive foo or bar elements is dynamic. Also, assume the markup cannot be modified in any way.

Selecting adjacent elements is pretty straight forward:

CSS

.foo + .foo, 
.bar + .bar { /* do something */ }

But selecting the last element in a series of consecutive elements, is that possible?

like image 778
technophobia Avatar asked Mar 22 '14 19:03

technophobia


People also ask

Is there a previous sibling selector?

No, there is no "previous sibling" selector. On a related note, ~ is for general successor sibling (meaning the element comes after this one, but not necessarily immediately after) and is a CSS3 selector. + is for next sibling and is CSS2. 1.

What is general sibling selector?

The general sibling selector (~) selects all elements that are next siblings of a specified element.

What is adjacent sibling selector?

The adjacent sibling selector is used to select an element that is directly after another specific element. Sibling elements must have the same parent element, and "adjacent" means "immediately following".

Which of the following selectors selects all sibling elements?

The ("element ~ siblings") selector selects sibling elements that appear after the specified "element".


1 Answers

The CSS support for :has is still poor but it can solve the problem:

/* selects any .foo that has no .foo immediately after it  */
.foo:has(+ :not(.foo)) {}
like image 86
Vahid Avatar answered Oct 30 '22 15:10

Vahid