Search code examples
csscss-selectorssiblings

Select last child when odd, 2 last childs when even


I'm in a situation where the number of elements shown is variable, and I need a strange solution that 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 children 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.

Does anyone have any idea/advice about this issue besides adding a class "odd" like on HTML tables?

Thanks a lot in advance!


Solution

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