不是:第一个孩子选择器

CSS

猪猪西门

2020-03-16

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

第1686篇《不是:第一个孩子选择器》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

8个回答
猿Gil 2020.03.16

我没有以上这些运气,

这是唯一真正为我工作的人

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

当我尝试使页面上显示的第一个按钮不受左空白选项影响时,这对我有用。

这是我首先尝试的选项,但是没有用

ul:not(:first-child)

理查德小小 2020.03.16

您可以将选择器与:not波纹管一起使用,也可以在内部使用任何选择器:not()

any_CSS_selector:not(any_other_CSS_selector){
    /*YOUR STYLE*/
}

您也可以:not使用父选择器。

   :not(:nth-child(2)){
        /*YOUR STYLE*/
   }

更多例子

any_CSS_selector:not(:first-child){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:first-of-type){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:checked){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:last-child){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:last-of-type){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:first-of-type){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:nth-last-of-type(2)){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:nth-last-child(2)){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:nth-child(2)){
    /*YOUR STYLE*/
}
EvaAPro 2020.03.16

这个CSS2解决方案(“一个ul又一个ul”)也可以工作,并且得到更多浏览器的支持。

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

不同于:not:nth-siblingIE7 +支持相邻的兄弟选择器

如果在页面加载后JavaScript更改了这些属性,则应查看IE7IE8实现中的一些已知错误请参阅此链接

对于任何静态网页,这应该都能正常工作。

西里GO 2020.03.16
div li~li {
    color: red;
}

支持IE7

L卡卡西 2020.03.16

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

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

因此,您可以选择ul其父元素中的每个元素(第一个元素除外)

有关更多示例,请参阅Chris Coyer的“有用的第n个孩子的食谱”一nth-child

理查德小小 2020.03.16

您可以将任何选择器用于 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)){}
逆天十三 2020.03.16

一个您发布的版本的实际工作为所有现代浏览器(如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.03.16

not(:first-child)似乎不再起作用。至少使用更新版本的Chrome和Firefox。

相反,请尝试以下操作:

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android