我如何使用CSS3选择器选择除最后一个子之外的所有子?

例如,如果只获取最后一个子元素,则使用div:n -last-child(1)。


当前回答

如果你在父类的嵌套中使用它,那么最简单的方法是:

&:not(:last-child){
  ....
}

例子:

.row {  //parent
 ...
 ...
 ...
 &:not(:last-child){
  ....
 }
}

其他回答

如果你在父类的嵌套中使用它,那么最简单的方法是:

&:not(:last-child){
  ....
}

例子:

.row {  //parent
 ...
 ...
 ...
 &:not(:last-child){
  ....
 }
}

当IE9到来时,这将变得更容易。但是很多时候,你可以把问题切换到一个要求:first-child和样式元素的反面(IE7+)。

在css3中有一个:not选择器。使用:not()和:last-child一起选择除最后一个外的所有子元素。例如,要选择ul中除了最后一个li之外的所有li,使用以下代码。

ul li:not(:last-child){   }

Nick Craver的解决方案是可行的,但你也可以用这个:

:nth-last-child(n+2) { /* Your code here */ }

CSS Tricks的Chris Coyier做了一个很好的测试:第n个测试者。

Nick Craver的解决方案给了我我所需要的,但让那些使用CSS-in-JS的人明确:

const styles = {
  yourClass: {
    /* Styles for all elements with this class */
    '&:not(:last-child)': {
      /* Styles for all EXCEPT the last element with this class */
    },
  },
};