Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I style all <li> except for the fifth and sixth using nth-child()

I have a simple list:

<ul>
    <li>Test</li>
    <li>Test1</li>
    <li>Test2</li>
    <li>Test3</li>
    <li>Test4</li>
    <li>Test5</li>
    <li>Test6</li>
    <li>Test7</li>
</ul>

I'd like to give all <li> a color of red except for the 5 + 6

http://jsfiddle.net/7yDGg/1/

Can this be done using only one selector?

like image 428
Adrift Avatar asked Mar 19 '13 03:03

Adrift


2 Answers

Use css selector :not(target) to explicitly select which child is going to be excluded. replace the target with another selector.

We can combine selector :not() and :nth-child() to exclude specific elements.

For example in this case, we want to exclude the 5th and 6th element, then use this: :not(:nth-child(5)) and :not(:nth-child(6)).

ul li:not(:nth-child(5)):not(:nth-child(6)) {
    color: red; 
}
<ul>
    <li>Test 1</li>
    <li>Test 2</li>
    <li>Test 3</li>
    <li>Test 4</li>
    <li>Test 5</li>
    <li>Test 6</li>
    <li>Test 7</li>
</ul>
like image 85
novalagung Avatar answered Oct 25 '22 15:10

novalagung


The easiest way is this:

ul li {
    color: red;
}
ul li:nth-child(5), ul li:nth-child(6) {
    color: black;
}

fiddle updated.

like image 33
hjpotter92 Avatar answered Oct 25 '22 13:10

hjpotter92