您可以选择pure CSS中的一半元素...直到某一点。
唯一的缺点是你必须知道总项目的最大数量。可能是150,但它会再不行用151
在这里工作是一个演示:http://jsfiddle.net/tcK3F/(*)
最小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;
}
基于一个想法:
诀窍是从AndréLuís在Lea Verou的帖子中看到:Styling elements based on sibling count。我将其改编为您需要拆分的选择。
快速的解释:
:nth-last-child(-n+3)
将选择从父3件最后物品; :nth-child(n+3)
将选择除第一个 3个之外的所有项目。将它们结合起来,你可以根据它们后面的内容(或父母中有多少个孩子)来选择纯CSS中的元素。除非你需要将它们中的75个与74个逗号相结合,如果你想让这个技巧与150个元素一起工作......:)
兼容性是IE9 +(JS polyfills存在)
(*)
的HTML代码第一部分:偶数的列表项;
第二部分:奇数的列表项
第一CSS规则:将从2N项或最后N + 1从2N/2项+ 1选择最后N和在白色样式它们在蓝色(例如:在3项共5或6)。
第二个CSS规则:将从2N项目中选择最后N个或从2N + 1中选择最后N-1/2个项目,并用红色边框和斜体(例如总共4个或5个中的2个项目)进行样式设计
Yeah ,你必须使用JavaScript; CSS无法确定有多少个元素或用于指定数量的语法。 – 2013-03-17 22:18:32
那么,你会选择所有?刚刚也知道中间在哪里? – caramba 2013-03-17 22:19:03
@DavidThomas检查我的答案,确定CSS中有多少元素(链接到Lea Verou的帖子)并指定一个数量:':(first/last) - (of-type/child)(aN + b)'允许。除了M个第一个元素外,还有'li + li + li + li'。你不能做的事情是**算术**,并计算一个*真正的*未定义的元素数量(虽然DOM不大可能有未定义数量的元素,在*大多数情况下) – FelipeAls 2013-03-19 07:32:23