Valius79 Valius79 - 3 months ago 6
CSS Question

CSS Child Descendants

I just saw this question that is answered correctly here on Stack.

The question was how to select the first two li after each .class1 element.

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


This was the (great) correct and accepted 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 + * + * {...}


Now, I was playing around with this and was wondering why this doesn't work:

li.class1 li:nth-child(-n+2) {color:red;}


But works this way:

li:nth-child(-n+2) {color:red;}

Answer

Because when you use

li.class1 li:nth-child(-n+2) {color:red;} 

you are catching that li element and you are looking for his child but li elements here doesn't have any child so it won't work. If ul would have class 'class1' maybe it would work like you want.