Choose the last child when it is odd, the last 2 children when

I am in a situation where the number of displayed elements is variable, and I need a strange solution that I can not achieve, I even doubt that this is possible only with css.

I need to select last-child if my number of elements is odd, and last 2nd child if the number of elements is even.

I tried with nth-last-child :not(:nth-last-child()) , odd and even, but never got a good solution.

Does anyone have any ideas / advice on this issue regarding adding the "odd" class, for example, to html tables?

Many thanks!

+5
source share
3 answers

Here is one way ...

 .wrap div:last-child, .wrap div:nth-last-of-type(-n+2):not(:nth-child(even)) { color: red; } 
 <div class="wrap"> <div>Odd</div> <div>Even</div> <div>Odd</div> <div>Even</div> <div>Odd</div> <div>Even</div> </div> <hr> <div class="wrap"> <div>Odd</div> <div>Even</div> <div>Odd</div> <div>Even</div> <div>Odd</div> </div> 
+14
source

You can use CSS like this:

 li:last-child:nth-child(odd) { /* Last child AND odd */ background: red; } li:nth-last-child(2):nth-child(odd), li:last-child:nth-child(even) { /* Before last child AND odd */ /* Last child AND even */ background: green; } 

Demo: https://jsfiddle.net/hw0ehrhy/

+11
source

Absolutely this can be done using pure CSS. See full code below (odd child, last child red, even children, last 2 children green)

 <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ $('#but1').click(function(){ var count = $('p').length; if (count%2!=0) {$('div>p:last-child').css('background','red');} else {$('div>p:last-child').css('background','green');alert(count); $('div>p:nth-last-child(2)').css('background','green'); } }); }); </script> </head> <body> <button id=but1>Click</button> <div> <p>This is one. </p> <p> This is two. </p> <p> This is three. </p> <p> This is four. </p> <p> This is five. </p> <p> This is six. </p> </div> </body> </html> 

Enjoy, coding;)

-4
source

All Articles