I'm in a situation where the number of elements showed is variable, and I need a strange solution which I'm not able to achieve, I even doubt if it's achievable only with css.
I need to select the last-child if my number of elements is odd, and the last 2 child if the number of elements is even.
I've been trying with nth-last-child
, :not(:nth-last-child())
, odd and even, but never got a good solution.
Anyone has any idea/advice about this issue a part of adding a class "odd" like on html tables?
Thanks a lot in advance!
You can use CSS like so:
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/
Absolutely it can be done, with pure CSS. See the complete code below (odd child, last child red; even childs, last 2 childs 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, the coding ;)