我想要选取一个无序列表中的前两个列表项。目前我可以用以下方式选取第一个列表项:
ul li:nth-child(1) a {
background: none repeat scroll 0 0 beige;
}
或者
ul li:first-child a {
background: none repeat scroll 0 0 beige;
}
我想选择第一和第二行项目 - 我该怎么做?
我想要选取一个无序列表中的前两个列表项。目前我可以用以下方式选取第一个列表项:
ul li:nth-child(1) a {
background: none repeat scroll 0 0 beige;
}
或者
ul li:first-child a {
background: none repeat scroll 0 0 beige;
}
我想选择第一和第二行项目 - 我该怎么做?
要选择第一个和第二个子元素,您可以使用单个:nth-child()
伪类,方法如下:
ul li:nth-child(-n+2) a {
background: none repeat scroll 0 0 beige;
}
如果不使用JavaScript或:nth-child
(我认为在IE中不支持)
ul li:first-child, ul li:first-child + li {
list-style: none;
}
这里是在IE7中测试过的演示。
:first-child
和相邻兄弟选择器来说非常棒,适用于从 IE7 开始的所有版本,有很好的兼容性。 - BoltClock这段代码在IE9及以上版本中可以运行,但不是最短的解决方案。@BoltClock的选择器是适用于IE9+最短的解决方案。我认为这个解决方案稍微容易理解一些,因此我会把它作为备选方案。
ul li:first-child a, ul li:nth-child(2) a
{
background: none repeat scroll 0 0 biege;
}
an + b
,您只需传递一个负数的 a
,它就会仅选择前 b
个子元素。请参阅我的答案。 - BoltClock可以尝试类似于以下代码:
$( function() {
$('li').each( function() {
if( $(this).index() == 1 || $(this).index() == 2 ) {
$(this).addClass('first_or_second');
}
});
});
.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; }
a=-1
。 - tvanfosson