Html 用css选择倒数第二个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5418744/
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
Select second last element with css
提问by dynamic
I already know of :last-child. But is there a way to select the div:
我已经知道:last-child。但是有没有办法选择div:
<div id="container">
<div>a</div>
<div>b</div>
<div>SELECT THIS</div> <!-- THIS -->
<div>c</div>
</div>
NOTE: without jQuery, only with CSS
注意:没有 jQuery,只有 CSS
回答by Frosty Z
In CSS3 you have:
在 CSS3 中,你有:
:nth-last-child(2)
See: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child
请参阅:https: //developer.mozilla.org/en-US/docs/Web/CSS/: nth-last-child
nth-last-childBrowser Support:
nth-last-child浏览器支持:
- Chrome 2
- Firefox 3.5
- Opera 9.5, 10
- Safari 3.1, 4
- Internet Explorer 9
- 铬 2
- 火狐 3.5
- 歌剧 9.5, 10
- Safari 3.1、4
- 浏览器 9
回答by kapa
Note:Posted this answer because OP later stated in comments that he needs to select the last two elements, not just the penultimate one.
注意:发布此答案是因为 OP 后来在评论中指出他需要选择最后两个元素,而不仅仅是倒数第二个。
The :nth-child
CSS3 selector is in fact more capable than you ever imagined!
该:nth-child
CSS3选择器,其实是更有能力比你想象!
For example, this will select the last 2 elements of #container
:
例如,这将选择 的最后 2 个元素#container
:
#container :nth-last-child(-n+2) {}
But this is just the beginning of a beautiful friendship.
但这只是一段美好友谊的开始。
#container :nth-last-child(-n+2) {
background-color: cyan;
}
<div id="container">
<div>a</div>
<div>b</div>
<div>SELECT THIS</div>
<div>SELECT THIS</div>
</div>