Selecting half the elements with :nth-child?

You can select half of the elements in pure CSS... up to a point.
The only drawback is that you've to know the maximum number of total items. Could be 150 but it would then not work with 151.

Here's a demo: http://jsfiddle.net/tcK3F/ (*)

Minimal CSS:

/* selecting half or more items. Up to 6 */
li:first-child:last-child,
li:nth-child(n+2):nth-last-child(-n+2),
li:nth-child(n+3):nth-last-child(-n+3),
li:nth-child(n+4):nth-last-child(-n+4),
li:nth-child(n+5):nth-last-child(-n+5),
li:nth-child(n+6):nth-last-child(-n+6) {
  color: white;
  background: darkblue;
}

/* selecting half or less items. Up to 6 */
li:nth-child(n+2):last-child,
li:nth-child(n+3):nth-last-child(-n+2),
li:nth-child(n+4):nth-last-child(-n+3),
li:nth-child(n+5):nth-last-child(-n+4),
li:nth-child(n+6):nth-last-child(-n+5),
li:nth-child(n+7):nth-last-child(-n+6){
  font-style: italic;
  border: 2px solid red;
}

Based on an idea from:
The trick is from André Luís and seen in a post from Lea Verou: Styling elements based on sibling count. I adapted it to your need of a split selection.

Quick explanation:
:nth-last-child(-n+3) will select the 3 last items from a parent; :nth-child(n+3) will select all items except the first 3 ones. Combine them and you can select elements in pure CSS based on what follow them (or how many children are in a parent). Except you'll have to combine 75 of them with 74 commas if you want this trick to work with 150 elements... :)

Compatibility is IE9+ (JS polyfills exist)

(*)
first part of HTML code: even number of list items;
second part: odd number of list items

first CSS rule: will select last N from 2N items or last N+1/2 items from 2N+1 and style them in white on blue (ex: 3 items in a total of 5 or 6).
second CSS rule: will select last N from 2N items or last N-1/2 items from 2N+1 and style them with red border and italic (ex: 2 items in a total of 4 or 5)


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.


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