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

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


当前回答

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

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

其他回答

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

<style>
ul li:not(:last-child){ color:#a94442}  
</style>
.nav-menu li:not(:last-child){
    // write some style here
}

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

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

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

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

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

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

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 */
    },
  },
};