Giann Dall Giann Dall - 3 months ago 7
CSS Question

Is there a CSS selector for continuous siblings

I have a list as this:

<ul>
<li>Something</li>
<li class="class1">Important</li>
<li>I want this</li>
<li>I want this</li>
<li class="class1">Important</li>
<li>I want this</li>
<li>I want this</li>
<li>Something</li>
<li>Something</li>
</ul>


Is there a CSS selector for the fist two
<li>
after each
.class1
element?

Answer

.class1 + li will select the first subsequent sibling.
.class1 + * + li will select the second.

to keep specificity low, you could also use:

.class1 + *,
.class1 + * + * {...}

but that's with the understanding that .class1 only ever selects the appropriate li elements.


Both of these are fragile selectors. Fragile in that they will break when you change the markup even a little. Consider just adding more classes to target the appropriate elements, and keep your specificity low.