Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select last two element in div but not if there are only two

I'd like to use nth-child to select the last two element in a div. I know that I can do this using nth-child(-n+2). But if there are only two element in there, it shouldn't select anything. How can I achive this?

like image 462
Lupin Avatar asked Dec 01 '25 10:12

Lupin


1 Answers

you can also consider nth-last-child() and create a complex selector like below:

.container {
  border:2px solid red;
}
.container * {
  height:10px;
  margin:5px;
  background:blue;
}

.container *:nth-last-child(-n + 2):not(:nth-child(-n + 2)), /* select last two that aren't first two*/
.container *:nth-last-child(2):nth-child(2) { /* select the second when there is 3 items */
  background:green;
}
<div class="container">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
<div class="container">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

<div class="container">
    <div></div>
    <div></div>
    <div></div>
</div>

<div class="container">
    <div></div>
    <div></div>
</div>

<div class="container">
    <div></div>
</div>
like image 56
Temani Afif Avatar answered Dec 04 '25 01:12

Temani Afif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!