Html nth-child() 还是第一个孩子?如何选择第一个和第二个孩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8821193/
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
nth-child() or first-child? how to select first AND second child in one
提问by Doug Fir
I'd like to select the first two list items in an unordered list. I can select the first item thus:
我想在无序列表中选择前两个列表项。我可以这样选择第一项:
ul li:nth-child(1) a {
background: none repeat scroll 0 0 beige;
}
OR
或者
ul li:first-child a {
background: none repeat scroll 0 0 beige;
}
I'd like to select both the first and second line item - how do I do that?
我想同时选择第一行和第二行 - 我该怎么做?
回答by BoltClock
For selecting the first and second children, you can use a single :nth-child()
pseudo-class like so:
要选择第一个和第二个孩子,您可以使用一个:nth-child()
伪类,如下所示:
ul li:nth-child(-n+2) a {
background: none repeat scroll 0 0 beige;
}
回答by T I
回答by tvanfosson
This works in IE9+ but it's not the shortest. @BoltClock's selector is the shortest solution for IE9+. I think this one is marginally easier to understand so I'll leave it as an alternative.
这适用于 IE9+,但不是最短的。@BoltClock 的选择器是 IE9+ 的最短解决方案。我认为这个更容易理解,所以我将其作为替代方案。
ul li:first-child a, ul li:nth-child(2) a
{
background: none repeat scroll 0 0 biege;
}
回答by sethasaurus
Your best bet for cross-browser compatibility would be to use jQuery and assign a class to the list item.
跨浏览器兼容性的最佳选择是使用 jQuery 并为列表项分配一个类。
Something like...
就像是...
$( function() {
$('li').each( function() {
if( $(this).index() == 1 || $(this).index() == 2 ) {
$(this).addClass('first_or_second');
}
});
});
回答by shabudeen shaikh
.trJobStatus ul{
width: 500px;
height:500px;
float: left;
}
.trJobStatus ul li{
width: 50px;
height:50px;
border: solid 1px #ddd;
list-style:none;
display: inline-block;
text-align: center;
line-height:50px;
font-size:25px;
}
.trJobStatus ul li:nth-child(1),
.trJobStatus ul li:nth-child(5){
color:red;
}
<div class="trJobStatus">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
.trJobStatus ul li:nth-child(1), .trJobStatus ul li:nth-child(2) { color: #fff; background-color:#ddd; }
.trJobStatus ul li:nth-child(1), .trJobStatus ul li:nth-child(2) { color: #fff; 背景颜色:#ddd; }