n-child()还是第一个孩子?如何在一个中选择第一个和第二个孩子

问题描述:

我想在无序列表中选择前两个列表项。我可以这样选择第一项:n-child()还是第一个孩子?如何在一个中选择第一个和第二个孩子

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; 
} 

我想选择这两个第一和第二行项目 - 我该怎么做呢?

在不使用JS或:nth-child(我认为在IE不支持)

ul li:first-child, ul li:first-child + li { 
    list-style: none; 
} 

Here的是在IE7

+4

对于':first-child'和邻接的兄弟选择器+1,非常适合一直到IE7的兼容性。 – BoltClock 2012-01-11 15:09:51

这适用于IE9 +,但它不是最短的。 @ BoltClock的选择器是IE9 +的最短解决方案。我认为这个比较容易理解,所以我会把它作为一个选择。

ul li:first-child a, ul li:nth-child(2) a 
{ 
    background: none repeat scroll 0 0 biege; 
} 
+0

谢谢。所以我必须用逗号分隔每个选择器 - 没有办法在同一个选择器中选择两个选择器?我一直在思考一些问题:nth-​​child(1,2)a - 当然这不起作用,但我认为可能有类似的东西吗? – 2012-01-11 14:53:27

+0

@tvanfosson:使用'an + b',你可以简单地传递一个负面的'a',它会只拾取第一个'b'子。看到我的答案。 – BoltClock 2012-01-11 15:00:02

+0

@BoltClock - 我每天都会学到新的东西。 +1给你,但我会把它留在这里(经过一些考虑),因为我认为这很容易理解发生的事情。 – tvanfosson 2012-01-11 15:37:14

对于跨浏览器兼容性,最好的选择是使用jQuery并为列表项分配一个类。

喜欢的东西...

$(function() { 

$('li').each(function() { 
    if($(this).index() == 1 || $(this).index() == 2) { 
    $(this).addClass('first_or_second'); 
    } 
}); 

}); 
+1

浏览器没有JavaScript? – 2012-01-11 14:53:58

选择第一和第二的孩子,你可以使用一个:nth-child()伪类,像这样:

ul li:nth-child(-n+2) a { 
    background: none repeat scroll 0 0 beige; 
} 
+1

不错。我不知道如何使用'a = -1'。 – tvanfosson 2012-01-11 15:03:31

.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; }