如何使用CSS选择器选择除first和last之外的所有子项

时间:2021-01-15 20:13:03

How would I select all the children in a table except for the first and last? I've tried this, but it ends up selecting all children that aren't first and all children that aren't last, which ends up being all children:

除了第一个和最后一个,我如何选择表格中的所有孩子?我已经尝试了这个,但它最终选择了所有不是第一个的孩子和所有不是最后的孩子,最终成为所有孩子:

table.programs tr td:not(:first-child), table.programs tr td:not(:last-child) {
}

I want all children that are neither first nor last. How can I do this?

我想要所有既不是第一也不是最后的孩子。我怎样才能做到这一点?

3 个解决方案

#1


53  

Use two :not() selectors combined, thereby referring to elements that match both of them, i.e. to elements that match neither of the selectors used as operands of :not():

使用两个:not()选择器组合,从而引用与它们相匹配的元素,即与既不匹配用作操作数的选择器的元素:not():

table.programs td:not(:first-child):not(:last-child)

#2


3  

The jQuery solution is fine, but if you want to do it in pure CSS I'd suggest you to apply the rules to the whole table and then reset them for the first and last children. i.e:

jQuery解决方案很好,但如果您想在纯CSS中执行此操作,我建议您将规则应用于整个表,然后为第一个和最后一个子节点重置它们。即:

table.programs tr td { 
  /* your rules here */
}

table.programs tr:first-child td:first-child, 
table.programs tr:last-child td:last-child {
  /* reset your rules here */
}

jsFiddle demo

jsFiddle演示

#3


2  

I think this should work for you:

我认为这对你有用:

table.programs tr td:not(:first-child,:last-child)

#1


53  

Use two :not() selectors combined, thereby referring to elements that match both of them, i.e. to elements that match neither of the selectors used as operands of :not():

使用两个:not()选择器组合,从而引用与它们相匹配的元素,即与既不匹配用作操作数的选择器的元素:not():

table.programs td:not(:first-child):not(:last-child)

#2


3  

The jQuery solution is fine, but if you want to do it in pure CSS I'd suggest you to apply the rules to the whole table and then reset them for the first and last children. i.e:

jQuery解决方案很好,但如果您想在纯CSS中执行此操作,我建议您将规则应用于整个表,然后为第一个和最后一个子节点重置它们。即:

table.programs tr td { 
  /* your rules here */
}

table.programs tr:first-child td:first-child, 
table.programs tr:last-child td:last-child {
  /* reset your rules here */
}

jsFiddle demo

jsFiddle演示

#3


2  

I think this should work for you:

我认为这对你有用:

table.programs tr td:not(:first-child,:last-child)