Joe*_*oeJ 11 html css css-selectors
以下面的代码为例:
<ul>
<li>Hello World</li>
<li>Hello World</li>
<li>Hello World</li>
<li>Hello World</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
是否可以使用:nth-child()或以其他方式精确选择总元素的一半?代码应该在上面的例子中选择第一个/最后两个 li,然后如果我要将lis 的数量增加到6,它将选择第一个/最后三个.
我觉得我将不得不使用JavaScript ...
Fel*_*Als 14
您可以选择纯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;
}
Run Code Online (Sandbox Code Playgroud)
基于以下思路:
诀窍来自AndréLuís,并在Lea Verou的帖子中看到:基于兄弟计数的造型元素.我根据你的需要选择了它.
快速说明:
:nth-last-child(-n+3)将从父母中选择最后 3 项; :nth-child(n+3)将选择除前 3个项目之外的所有项目.结合它们,你可以根据它们的后续内容(或者父项中有多少个孩子)选择纯CSS中的元素.如果你想要这个技巧与150个元素一起使用,你必须将它们中的75个与74个逗号结合起来... :)
兼容性是IE9 +(存在JS polyfill)
(*)
HTML代码的第一部分:偶数列表项;
第二部分:奇数列表项
第一个CSS规则:将从2N项目中选择最后N个,或者从2N + 1中选择最后N + 1/2个项目,并在蓝色上将它们设置为白色(例如:总共5个或6个中的3个项目).
第二个CSS规则:将从2N项目中选择最后N个,或者从2N + 1中选择最后N-1/2个项目,并使用红色边框和斜体来设置样式(例如:总共4个或5个中的2个项目)
在纯CSS中,您能够获得与之接近的唯一方法是对nth-child(odd)或进行选择nth-child(even)。如果您只需要最后一半(而不是奇数或偶数),则必须使用JavaScript / jQuery。
使用jQuery,您可以使用以下命令获取它们:
var yourList = $("ul li");
yourList = yourList.slice(0, Math.floor(yourList.length/2));
Run Code Online (Sandbox Code Playgroud)