nth-child() or first-child? how to select first AN

2019-02-03 03:21发布

问题:

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 scroll 0 0 beige;
}

OR

ul li:first-child a {
    background: none repeat scroll 0 0 beige;
}

I'd like to select both the first and second line item - how do I do that?

回答1:

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



回答2:

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


回答3:

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


回答4:

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

});


回答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) { color: #fff; background-color:#ddd; }