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

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


当前回答

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

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

其他回答

.nav-menu li:not(:last-child){
    // write some style here
}

这段代码应该将该样式应用于除最后一个子元素之外的所有元素

简单点:

你可以将你的样式应用到所有的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)

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

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

例子:

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

你可以对:last子伪类使用否定伪class:not()。引入CSS选择器Level 3后,它在IE8或以下版本中无法工作:

:not(:last-child) { /* styles */ }

使用更通用的选择器,可以实现如下所示

& > *:not(:last-child) {/* styles here */}

例子

<div class="parent">
  <div>Child one</div>
  <div>Child two</div>
</div>

这将捕获父节点中的所有子DIV