我有一个div标签包含几个ul标签。

我只能为第一个ul标签设置CSS属性:

div ul:first-child {
    background-color: #900;
}

然而,我下面的尝试为其他ul标签设置CSS属性除了第一个不工作:

div ul:not:first-child {
    background-color: #900;
}

div ul:not(:first-child) {
    background-color: #900;
}

div ul:first-child:after {
    background-color: #900;
}

我怎么能写在CSS:“每个元素,除了第一个”?


当前回答

li + li {
    background-color: red;
}

其他回答

由于:not不被IE6-8所接受,我建议你这样做:

div ul:nth-child(n+2) {
    background-color: #900;
}

所以你选择了父元素中的每个ul,除了第一个。

参考Chris Coyer的“有用的:第n个孩子的食谱”一文,了解更多关于第n个孩子的例子。

你发布的一个版本实际上适用于所有现代浏览器(支持CSS选择器级别3):

div ul:not(:first-child) {
    background-color: #900;
}

如果你需要支持旧浏览器,或者你被:not选择器的限制(它只接受一个简单的选择器作为参数)所阻碍,那么你可以使用另一种技术:

定义一个比你想要的范围更大的规则,然后有条件地“撤销”它,将其范围限制在你想要的范围内:

div ul {
    background-color: #900;  /* applies to every ul */
}

div ul:first-child {
    background-color: transparent; /* limits the scope of the previous rule */
}

在限制作用域时,使用您正在设置的每个CSS属性的默认值。

div ul::nth-child(n+2){
    background-color: #900;
}

也起作用了

li + li {
    background-color: red;
}

Not (:first child)似乎不再起作用了。至少最新版本的Chrome和Firefox是这样的。

相反,试试这个:

ul:not(:first-of-type) {}