我想使用nth-child
选择div中的最后两个元素。我知道我可以使用nth-child(-n+2)
执行此操作。但是,如果其中只有两个元素,则不应选择任何内容。我怎样才能做到这一点?
您也可以考虑nth-last-child()
并创建如下所示的复杂选择器:
.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>