注:这个解决scheme将返回一定长度的子集,而不是你所要求的父元素。 希望它仍然有用。
安德烈·路易斯提出了一个方法: http : //lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/不幸的是,它只适用于IE9及以上。
本质上,你将nnth-child()与其他处理元素位置的伪类结合起来。 这种方法允许您从具有特定长度的元素集合中指定元素。
例如:nth-child(1):nth-last-child(3)匹配集合中的第一个元素,同时也是集合的结尾的第三个元素。 这样做有两个方面:保证集合只有三个元素,而我们有三个元素中的第一个元素。 要指定三个元素集的第二个元素,我们使用:nth-child(2):nth-last-child(2) 。
示例1 – 如果set包含三个元素,则select所有列表元素:
li:nth-child(1):nth-last-child(3), li:nth-child(2):nth-last-child(2), li:nth-child(3):nth-last-child(1) { width: 33.3333%; }
来自Lea Verou的示例1替代scheme :
li:first-child:nth-last-child(3), li:first-child:nth-last-child(3) ~ li { width: 33.3333%; }
示例2 – 使用三个列表元素指定集合的最后一个元素:
li:nth-child(3):last-child { /* I'm the last of three */ }
例2替代:
li:nth-child(3):nth-last-child(1) { /* I'm the last of three */ }
示例3 – 以四个列表元素为目标的第二个元素:
li:nth-child(2):nth-last-child(3) { /* I'm the second of four */ }