我有一个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:“每个元素,除了第一个”?


当前回答

你可以使用not的任何选择器

p:not(:first-child){}
p:not(:first-of-type){}
p:not(:checked){}
p:not(:last-child){}
p:not(:last-of-type){}
p:not(:first-of-type){}
p:not(:nth-last-of-type(2)){}
p:not(nth-last-child(2)){}
p:not(:nth-child(2)){}

其他回答

div li~li {
    color: red;
}

支持IE7

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

相反,试试这个:

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

正如我使用ul:not(:first-child)是一个完美的解决方案。

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

为什么这是完美的,因为通过使用ul:not(:first-child),我们可以在内部元素上应用CSS。比如li, img, span, a标签等等。

但当使用其他解决方案时:

div ul + ul {
  background-color: #900;
}

and

div li~li {
    color: red;
}

and

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

and

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

这些只限制ul级别的CSS。假设我们不能将CSS应用于li作为' div ul + ul li'。

对于内部关卡元素,第一个解决方案非常有效。

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

等等……

你可以使用not的任何选择器

p:not(:first-child){}
p:not(:first-of-type){}
p:not(:checked){}
p:not(:last-child){}
p:not(:last-of-type){}
p:not(:first-of-type){}
p:not(:nth-last-of-type(2)){}
p:not(nth-last-child(2)){}
p:not(:nth-child(2)){}
div ul::nth-child(n+2){
    background-color: #900;
}

也起作用了