如何使用 css nth-child 选择列表中的最后 2 项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6604900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 00:56:46  来源:igfitidea点击:

How do I choose the last 2 items in a list with css nth-child?

csscss-selectors

提问by John

Is it possible? If not, is there a way to do it with jQuery?

是否可以?如果没有,有没有办法用 jQuery 做到这一点?

采纳答案by methodofaction

Unfortunately it's impossible.. Disregard this answer and look at spliters answer below.

不幸的是这是不可能的。. 忽略此答案并查看下面的拆分器答案

If it were to be possible, it would look something like...

如果有可能,它看起来会像……

ul li:last-child+li {...}

But this doesn't work, because + will select the immediate sibling afterlast-child (which is nothing, of course). There is no immediate previousselector.

但这不起作用,因为 + 将选择last-child之后的直接兄弟(当然,这没什么)。没有直接上一个选择器。

There are different ways of achieving this with jQuery, the most performant would be...

使用 jQuery 有多种不同的方法可以实现这一点,最高效的方法是......

var lastItems = $("#list li");
lastItems.slice(lastItems.length - 2).addClass("whatever");

http://jsfiddle.net/qkzdJ/

http://jsfiddle.net/qkzdJ/

回答by spliter

It is possible with CSS3. Consider the markup:

使用 CSS3 是可能的。考虑标记:

<ul>
    <li><a href="">First item</a></li>
    <li>Second item</li>
    <li><a href="">Test</a></li>
    <li><a href="">Test</a></li>
    <li><a href="">Pre-last item</a></li>
    <li><a href="">Last item</a></li>
</ul>

To choose the last two LI elements you do:

要选择最后两个 LI 元素,请执行以下操作:

ul > li:nth-last-of-type(-n+2) {
    background: green;
}

Works in all contemporary browsers including IE9, but excluding IE8 and below. To add support for those browsers, you might consider using Selectivizr.js

适用于所有现代浏览器,包括 IE9,但不包括 IE8 及更低版本。要添加对这些浏览器的支持,您可以考虑使用Selectivizr.js

回答by katsampu

:last-child,
:nth-last-child(2) {
  ruleset
}

will play as well.

也会玩。

回答by Anchor_Chisel

For me it was this: li:not(:nth-last-child(-n+2))

对我来说是这样的: li:not(:nth-last-child(-n+2))