Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select last child when odd, 2 last childs when even

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!

like image 641
agapitocandemor Avatar asked Apr 21 '15 11:04

agapitocandemor


People also ask

How do you select all child elements except last?

When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.

How do you select the last child in selenium?

13) Using *:last-of-type CSS Selector in Selenium You can use “*last-of-type”. It will select the last child of the parent tag. Syntax: . tree-branch>ul>*:last-of-type (Selects the last child of parent tag “ul”.)


2 Answers

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/

like image 61
Bluety Avatar answered Oct 21 '22 07:10

Bluety


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>
like image 20
Turnip Avatar answered Oct 21 '22 06:10

Turnip