小编典典

不是:第一个子选择器

css

我有一个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中编写“除第一个元素外的每个元素”?


阅读 341

收藏
2020-05-16

共1个答案

小编典典

一个您发布的版本的实际工作为所有现代浏览器(如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属性使用默认值。

2020-05-16