首页 文章

我怎样才能使用not:first-child选择器?

提问于
浏览
626

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

6 回答

  • 132

    好吧,因为 IE6~8 不接受 :not ,我建议你这样做:

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

    所以你在其父元素中选择每个 ul 除了第一个 .

    有关详细信息,请参阅Chris Coyer的 "Useful :nth-child Recipes" 文章 nth-child examples .

  • 14

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

    相反,试试这个:

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

    您为所有现代浏览器发布的其中一个版本actually works(其中CSS selectors level 3supported):

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

    如果您需要支持旧版浏览器,或者如果您受到 :not 选择器的limitation(它只接受simple selector作为参数)的阻碍,那么您可以使用另一种技术:

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

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

    限制范围时,请对要设置的每个CSS属性使用default value .

  • 2
    div li~li {
        color: red;
    }
    

    支持IE7

  • 1079

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

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

    :not:nth-sibling 不同,IE7支持adjacent sibling selector .

    如果在页面加载后有 JavaScript 更改这些属性,您应该查看 IE7IE8 实现中的一些已知错误 . See this link .

    对于任何静态网页,这应该是完美的 .

  • 64

    上面的一些我没有运气,

    这是唯一一个真正适合我的人

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

    当我试图让页面上显示的第一个按钮不受左边距选项影响时,这对我有用 .

    这是我先尝试的选项,但它不起作用

    ul:not(:first-child)

相关问题