nth-child() 还是 first-child?如何同时选择第一个和第二个子元素?

32

我想要选取一个无序列表中的前两个列表项。目前我可以用以下方式选取第一个列表项:

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

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

5个回答

62

要选择第一个和第二个子元素,您可以使用单个:nth-child()伪类,方法如下:

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

2
不错。我不知道可以使用 a=-1 - tvanfosson

50

如果不使用JavaScript或:nth-child(我认为在IE中不支持)

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

这里是在IE7中测试过的演示。


5
+1 对于 :first-child 和相邻兄弟选择器来说非常棒,适用于从 IE7 开始的所有版本,有很好的兼容性。 - BoltClock

5

这段代码在IE9及以上版本中可以运行,但不是最短的解决方案。@BoltClock的选择器是适用于IE9+最短的解决方案。我认为这个解决方案稍微容易理解一些,因此我会把它作为备选方案。

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

谢谢。所以我必须通过逗号分隔每个选择器 - 没有办法在同一个选择器中同时选择两个吗?我想到的是类似于 ul li:nth-child(1,2) a 的东西 - 当然这行不通,但我想可能会有类似的东西可以实现? - Doug Fir
@tvanfosson:使用 an + b,您只需传递一个负数的 a,它就会仅选择前 b 个子元素。请参阅我的答案。 - BoltClock
@BoltClock - 我每天都在学习新东西。给你点赞,但我会把我的留在这里(经过一些考虑),因为我认为这样更容易理解正在发生的事情。 - tvanfosson
确实,我就要点击您的回答上的“撤消删除”按钮了 :) - BoltClock

3
您想要实现跨浏览器兼容性,最好的方法是使用jQuery并将类分配给列表项。

可以尝试类似于以下代码:

$( function() {

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

});

1

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接