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

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


当前回答

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

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

例子:

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

其他回答

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

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

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

使用nick craver的解决方案与selectivizr允许跨浏览器解决方案(IE6+)

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

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

例子:

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

要查找last中的元素,请使用

<style>
ul li:not(:last-child){ color:#a94442}  
</style>

简单点:

你可以将你的样式应用到所有的div上,并使用:last-child重新初始化最后一个div:

例如在CSS中:

.yourclass{
    border: 1px solid blue;
}
.yourclass:last-child{
    border: 0;
}

或在SCSS:

.yourclass{
    border: 1px solid rgba(255, 255, 255, 1);
    &:last-child{
        border: 0;
    }
}

易于阅读/记忆 执行速度快 浏览器兼容(IE9+,因为它还是CSS3)