CSS last-child(-1)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9227932/
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
CSS last-child(-1)
提问by Hedde van der Heide
I am looking for a css selector that lets me select the pre-last child of list.
我正在寻找一个 css 选择器,它可以让我选择列表的前最后一个子项。
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li> <!-- select the pre last item dynamically no matter how long this list is -->
<li>6</li>
</ul>
Static method:
静态方法:
ul li:nth-child(5)
Dynamic method:
动态方法:
ul li:last-child(-1)
which of course doesn't validate, also nth-last-child doesn't seem to provide a dynamic way.. I can fallback to javascript but I'm wondering if there is a css way I overlooked
这当然没有验证,而且 nth-last-child 似乎也没有提供动态方式..我可以回退到 javascript,但我想知道是否有我忽略的 css 方式
回答by BoltClock
You canuse :nth-last-child()
; in fact, besides :nth-last-of-type()
I don't know what else you could use. I'm not sure what you mean by "dynamic", but if you mean whether the style applies to the new second last child when more children are added to the list, yes it will. Interactive fiddle.
你可以使用:nth-last-child()
; 事实上,除了:nth-last-of-type()
我不知道你还能用什么。我不确定你所说的“动态”是什么意思,但如果你的意思是当更多的孩子被添加到列表中时,样式是否适用于新的倒数第二个孩子,是的。交互式小提琴。
ul li:nth-last-child(2)
回答by David Allen
Unless you can get PHP to label that element with a class you are better to use jQuery.
除非您可以让 PHP 使用类来标记该元素,否则最好使用 jQuery。
jQuery(document).ready(function () {
$count = jQuery("ul li").size() - 1;
alert($count);
jQuery("ul li:nth-child("+$count+")").css("color","red");
});