Select last child when odd, 2 last childs when eve

2020-02-25 23:34发布

问题:

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!

回答1:

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>



回答2:

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/



回答3:

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