nth-child() or first-child? how to select first AND second child in one

前端 未结 5 876
再見小時候
再見小時候 2020-12-24 13:25

I\'d like to select the first two list items in an unordered list. I can select the first item thus:

ul li:nth-child(1) a {
    background: none repeat scrol         


        
相关标签:
5条回答
  • 2020-12-24 13:50

    Your best bet for cross-browser compatibility would be to use jQuery and assign a class to the list item.

    • http://api.jquery.com/eq-selector/
    • http://api.jquery.com/index/

    Something like...

    $( function() {
    
     $('li').each( function() {
       if( $(this).index() == 1 || $(this).index() == 2 ) {
         $(this).addClass('first_or_second');
       }
     });
    
    });
    
    0 讨论(0)
  • 2020-12-24 14:04

    Without the use of js or :nth-child (which I believe is not supported in IE)

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

    Here is a demo tested in IE7

    0 讨论(0)
  • 2020-12-24 14:04

    .trJobStatus ul{
        width: 500px;
      height:500px;
        float: left;
      }
    .trJobStatus ul li{
       width: 50px;
      height:50px;
      border: solid 1px #ffffd;
      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:#ffffd; }

    0 讨论(0)
  • 2020-12-24 14:08

    For selecting the first and second children, you can use a single :nth-child() pseudo-class like so:

    ul li:nth-child(-n+2) a {
        background: none repeat scroll 0 0 beige;
    }
    
    0 讨论(0)
  • 2020-12-24 14:12

    This works in IE9+ but it's not the shortest. @BoltClock's selector is the shortest solution for IE9+. I think this one is marginally easier to understand so I'll leave it as an alternative.

    ul li:first-child a, ul li:nth-child(2) a
    {
       background: none repeat scroll 0 0 biege;
    }
    
    0 讨论(0)
提交回复
热议问题