Search code examples
htmlcsscss-selectors

Selecting half the elements with :nth-child?


Take the following code for instance:

<ul>
  <li>Hello World</li>
  <li>Hello World</li>
  <li>Hello World</li>
  <li>Hello World</li>
</ul>

Is it possible, using :nth-child() or otherwise, to select exactly half of the total elements? The code should select the first/last two lis in the above instance, then if I were to increase the number of lis to six, it would select the first/last three.

I feel I'm going to have to use JavaScript...


Solution

  • The only way you'd be able to get anywhere near to that in pure CSS is to do a selector on either nth-child(odd) or nth-child(even). If you want exactly the last half (and not either odd or even), then you'd have to use JavaScript/jQuery.

    Using jQuery, you could get them using:

    var yourList = $("ul li");
    
    yourList = yourList.slice(0, Math.floor(yourList.length/2));