Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
285 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...