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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With