CSS 是否可以选择带有 nth-child 的最后 n 个项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4844456/
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
Is it possible to select the last n items with nth-child?
提问by DisgruntledGoat
Using a standard list, I'm trying to select the last 2 list items. I've various permutations of An+B
but nothing seems to select the last 2:
使用标准列表,我试图选择最后 2 个列表项。我有各种排列,An+B
但似乎没有选择最后两个:
li:nth-child(n+2) {} /* selects from the second onwards */
li:nth-child(n-2) {} /* selects everything */
li:nth-child(-n+2) {} /* selects first two only */
li:nth-child(-n-2) {} /* selects nothing */
I'm aware of a new CSS3 selectors like :nth-last-child()
but I'd prefer something that works in a few more browsers if possible (don't care about IE particularly).
我知道一个新的 CSS3 选择器,:nth-last-child()
但如果可能的话,我更喜欢在更多浏览器中工作的东西(特别不关心 IE)。
回答by John Guise
This will select the last two iems of a list:
这将选择列表的最后两个 iem:
li:nth-last-child(-n+2) {color:red;}
<ul>
<li>fred</li>
<li>fred</li>
<li>fred</li>
<li>fred</li>
<li>fred</li>
<li>fred</li>
<li>fred</li>
<li>fred</li>
<li>fred</li>
<li>fred</li>
</ul>
回答by Pekka
nth-last-child
sounds like it was specifically designed to solve this problem, so I doubt whether there is a more compatible alternative. Support looks pretty decent, though.
nth-last-child
听起来它是专门为解决这个问题而设计的,所以我怀疑是否有更兼容的替代方案。不过,支持看起来相当不错。
回答by Danyl Sobolev
:nth-last-child(-n+2)
should do the trick
:nth-last-child(-n+2)
应该做的伎俩
回答by Pointy
Because of the definition of the semantics of nth-child
, I don't see how this is possible without including the length of the list of elements involved. The point of the semantics is to allow segregation of a bunch of child elements into repeating groups (edit- thanks BoltClock) or into a first part of some fixed length, followed by "the rest". You sort-of want the opposite of that, which is what nth-last-child
gives you.
由于 语义的定义,nth-child
如果不包括所涉及元素列表的长度,我看不出这是怎么可能的。语义的重点是允许将一堆子元素分离成重复的组(编辑- 感谢 BoltClock)或分离到某个固定长度的第一部分,然后是“其余部分”。你有点想要相反的东西,这就是nth-last-child
给你的。
回答by Nathan Anderson
If you are using jQuery in your project, or are willing to include it you can call nth-last-child
through its selector API (this is this simulated it will cross browser). Here is a linkto an nth-last-child
plugin. If you took this method of targeting the elements you were interested in:
如果你在你的项目中使用 jQuery,或者愿意包含它,你可以nth-last-child
通过它的选择器 API 调用(这是模拟的,它将跨浏览器)。这里是一个链接到一个nth-last-child
插件。如果您采用这种方法来定位您感兴趣的元素:
$('ul li:nth-last-child(1)').addClass('last');
And then style again the last
class instead of the nth-child
or nth-last-child
pseudo selectors, you will have a much more consistent cross browser experience.
然后风格再次last
类,而不是nth-child
或nth-last-child
伪选择,你将有一个更加一致的跨浏览器体验。