Selecting half the elements with :nth-child?

前端 未结 3 1431
迷失自我
迷失自我 2020-12-06 05:36

Take the following code for instance:

  • Hello World
  • Hello World
  • Hello World
  • &
3条回答
  •  臣服心动
    2020-12-06 05:58

    Examples

    Create a CSS class with style for those elements:

    .half {
        background-color: #18D;
    }
    

    Then, use jQuery to add that class to the specified set of elements:

    $(function () {
      var $lis = $('ul li')
      var length = $lis.length
    
      // Add class to first half:
      $lis.slice(0, Math.floor(length / 2)).addClass('first')
    
      // Add class to last half:
      $lis.slice(length - Math.floor(length / 2)).addClass('first')
    })
    

    If you do want to include the element in the middle in the event of an odd amount of elements, change Math.floor to Math.ceil. All possibilities can be seen in the examples.

提交回复
热议问题