如果恰好有 5 个 child ,我想要所有 5 个 child 。(如果有 4 个或 6 个,不要选择任何 child 。)
举例说明:http://jsfiddle.net/rudiedirkx/339H6/3/show/
如果只有 1 个元素,您可以选择所有元素:
:first-child:last-child
您可以选择前 5 个和后 5 个中的元素:
:nth-child(-n+5):nth-last-child(-n+5)
(演示中为红色)两者都没有做我想要的,但说明了一点:1 个选择器,几个元素。
如果有 5 个有 5 个选择器,您可以选择所有子项:
li:nth-child(1):nth-last-child(5),
li:nth-child(2):nth-last-child(4),
li:nth-child(3):nth-last-child(3),
li:nth-child(4):nth-last-child(2),
li:nth-child(5):nth-last-child(1)
( fiddle 中的黄色)但这太可怕了。当我决定我也喜欢 4 时,这是双重可怕的:如果恰好有 4 或 5 个元素,请全部选择它们。这将需要 4 个以上的选择器。
有没有一种我缺少的体面的方法来做到这一点?我觉得 :nth-child(-n+5):nth-last-child(-n+5)
正在走上正轨,但选择范围太广了。 ( fiddle 中的绿色。)
最佳答案
在确定第一个 child 也是倒数第 5 个 child 后,您可以使用通用兄弟组合器选择其余元素:
li:first-child:nth-last-child(5),
li:first-child:nth-last-child(5) ~ li
不幸的是,您仍然需要至少重复选择器一次,因为您需要一个来匹配第一个子项,然后另一个与同级组合器匹配其余的。但这绝对胜过再重复四次。
关于css - 如果恰好有 5 个元素,则使用 CSS 选择所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16301291/