【发布时间】:2011-02-04 03:18:02
【问题描述】:
如何使用 CSS3 选择器选择除最后一个子元素之外的所有子元素?
例如,要仅获取最后一个孩子,则div:nth-last-child(1)。
【问题讨论】:
标签: css-selectors css
如何使用 CSS3 选择器选择除最后一个子元素之外的所有子元素?
例如,要仅获取最后一个孩子,则div:nth-last-child(1)。
【问题讨论】:
标签: css-selectors css
您可以将negation pseudo-class :not() 用于:last-child pseudo-class。引入 CSS 选择器 Level 3,它在 IE8 或更低版本中不起作用:
:not(:last-child) { /* styles */ }
【讨论】:
div)
&:not(:last-child) { /* styles * }。
您可以将您的样式应用到所有 div 并使用 :last-child:
重新初始化最后一个例如在 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;
}
}
【讨论】:
Nick Craver 的解决方案有效,但您也可以使用它:
:nth-last-child(n+2) { /* Your code here */ }
CSS Tricks 的 Chris Coyier 为此写了一个很好的 :nth tester。
【讨论】:
:not伪很贵。因此,尽可能避免它可能是个好主意。
:not 遍历整个级联以确定它是否适用(双关语),所以它的设计成本很高。在任何你能想到的情况下,你都可以轻松避免它。
IE9 来了,就更简单了。但很多时候,您可以将问题切换到需要 :first-child 并设置元素另一侧的样式(IE7+)。
【讨论】:
将 nick craver 的解决方案与 selectivizr 一起使用允许跨浏览器解决方案 (IE6+)
【讨论】:
.nav-menu li:not(:last-child){
// write some style here
}
此代码应将样式应用于所有
【讨论】:
要查找最后的元素,请使用
<style>
ul li:nth-last-of-type(3n){ color:#a94442} /**/
</style>
【讨论】:
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 */
},
},
};
【讨论】:
css3 中有一个:not 选择器。使用 :not() 和 :last-child 来选择除最后一个之外的所有孩子。例如,要选择 ul 中除最后一个 li 之外的所有 li,请使用以下代码。
ul li:not(:last-child){ }
【讨论】:
如果您在父级的嵌套中使用它,那么最简单的方法是:
&:not(:last-child){
....
}
示例:
.row { //parent
...
...
...
&:not(:last-child){
....
}
}
【讨论】: