【问题标题】:nth-child() or first-child? how to select first AND second child in onenth-child() 还是第一个孩子?如何选择第一个和第二个孩子
【发布时间】:2020-11-11 18:37:18
【问题描述】:

我想选择无序列表中的前两个列表项。我可以这样选择第一项:

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

我想同时选择第一个和第二个订单项 - 我该怎么做?

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    对于选择第一个和第二个孩子,您可以使用单个 :nth-child() 伪类,如下所示:

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

    【讨论】:

    • 不错。我不知道使用a=-1
    【解决方案2】:

    不使用js或者:nth-child(相信IE不支持)

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

    Here 是在 IE7 中测试的演示

    【讨论】:

    • +1 表示:first-child 和相邻的兄弟选择器,非常适合一直兼容到 IE7。
    【解决方案3】:

    这在 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 的东西 - 当然这不起作用,但我想可能有类似的东西吗?
    • @tvanfosson:使用an + b,您可以简单地传递一个否定的a,它只会拾取第一个b 孩子。看我的回答。
    • @BoltClock - 我每天都学到新东西。 +1 给你,但我会留在这里(经过一些考虑),因为我认为理解正在发生的事情稍微容易一些。
    • 确实,我已经接近点击取消删除的答案了 :)
    【解决方案4】:

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

    类似...

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

    【讨论】:

      【解决方案5】:

      .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) { 颜色:#fff; 背景颜色:#ddd; }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-09
        • 2022-06-28
        • 1970-01-01
        • 2022-11-02
        • 1970-01-01
        • 1970-01-01
        • 2012-08-16
        • 2011-08-16
        相关资源
        最近更新 更多