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?
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.
The general sibling selector (~) selects all elements that are next siblings of a specified element.
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".
The ("element ~ siblings") selector selects sibling elements that appear after the specified "element".
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)) {}
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