CSS nth-child - 一次性获取第1、2、4和5个子元素?

15

使用CSS3,我知道可以使用 nth-child(an + b) 选择器。我有一个包含5行的表格,我想用一条语句选择第1、2、4和5行。这是否可能,还是我必须至少使用两个语句,如下所示:

:nth-child(-n+2)  /* gets 1 and 2 */
:nth-child(n+4)   /* gets 4 and 5 */
我希望能使用类似于nth-child(1,2,4,5)nth-child(1-2,4-5) 的语法,但它似乎不属于规范的一部分。
(我无法控制页面,这些行上也没有ID/类。)
4个回答

29

如果你想表达得更明确,一种方法是像这样重复使用:nth-child()

tr:nth-child(1), tr:nth-child(2), tr:nth-child(4), tr:nth-child(5)

另外,由于表格恰好有5行,您可以直接排除第三行,这样您将获得第1、2、4和5行:

tr:not(:nth-child(3))

jsFiddle 预览


3
为了使其尽可能通用,您可以使用以下内容:
tr:not(:nth-child(1n+6)):not(:nth-child(3))  { 
    /* your rules here */
}

简单解释一下: 你说你想选择那些不是从第6个开始的元素(也就是前5个)并且不是第3个元素,如果你写成这样。
 tr:nth-child(1n+6) 

你选定了从第5行开始的行,因为你在选择行。
(1*0) + 6 [ = 6 ]
(1*1) + 6 [ = 7 ]
(1*2) + 6 [ = 8 ]
...等等。这就是表达式(1n + X)的含义,在我们的情况下,X 是 6。
在上面的表达式中添加 :not 伪选择器,表示您要选择不是从第5行开始的行,因此您将从第5行向下选择第1、2、3、4和第5行。
此外,再添加一个针对第三行的 :not 选择器,您将得到您想要的东西 => 前五行中没有第三行!
/***************** 更新!我添加了一个 jsfiddle *******************/
在这里,您可以看到它在这个 jsfiddle 中运作。

1

如果你使用了很多父级,你也可以使用:is符号。这不一定是更好的方法,但在我看来只是看起来更好一些。

所以,不要写成

.wrapper-class .another-class tr:nth-child(1), 
.wrapper-class .another-class tr:nth-child(2), 
.wrapper-class .another-class tr:nth-child(4), 
.wrapper-class .another-class tr:nth-child(5) {}

你得到

.wrapper-class .another-class tr:is(:nth-child(1),:nth-child(2),:nth-child(4),:nth-child(5)) {}

1
你可以始终使用 even 和 odd 关键字 例如: table tr:nth-child(even) 如果你想要表格数据,使用 table td:nth-child(odd)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接