3

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?

2
  • nth-of-type may be what you are looking for Commented Aug 16, 2016 at 17:31
  • 1
    Try reviewing this question Commented Aug 16, 2016 at 17:32

1 Answer 1

8

.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.

Sign up to request clarification or add additional context in comments.

10 Comments

The second selector reference is actually pretty neat.
@Martin, then the lobotomized owl selector may very well blow your mind.
@Aziz, I've never been in a situation where CSS selector performance mattered. I would hazard a guess that anyone running into selector performance problems has a bigger problem to solve (too many elements on the page).
"Both of these are fragile selectors. Fragile in that they will break when you change the markup even a little." Isn't that kind of the point? The OP only wants to target the two li elements that immediately follow each li with that class. There is no point bloating the markup by adding classes to each of the following two elements just to be able to target them if they will only ever appear in that context anyway - if you assigned those classes out of order, then the class selectors you propose would match incorrectly, and that's what I would call fragile.
@BoltClock, CSS is a declarative language, and as such it's beneficial to avoid attempting to describe deep relational paths when you can just use names. When I need my wife's father's brother's son's daughter to pass the potatoes, I just ask her by name. Going back to the issues of fragility here, if someone later removes a <li> such that the structure is .class1 + li + .class1 you will have an unintended behavior. These changes are quite common, and complex relational selectors make changes hard because the intent is obscured.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.