[英]nth-child() or first-child? how to select first AND second child in one
我想在无序列表中选择前两个列表项。 我可以这样选择第一项:
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;
}
不使用 js 或:nth-child
(我认为 IE 不支持)
ul li:first-child, ul li:first-child + li {
list-style: none;
}
这是在 IE7 中测试的演示
这适用于 IE9+,但不是最短的。 @BoltClock 的选择器是 IE9+ 的最短解决方案。 我认为这个更容易理解,所以我将其作为替代方案。
ul li:first-child a, ul li:nth-child(2) a
{
background: none repeat scroll 0 0 biege;
}
跨浏览器兼容性的最佳选择是使用 jQuery 并为列表项分配一个类。
就像是...
$( 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; 背景颜色:#ddd; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.