我有一个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中写上:"每个元素,除了第一个"?
你发布的其中一个版本[实际上可以][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属性使用默认值。
这个CSS2解决方案("任何ul
在另一个ul
之后")也可以使用,而且被更多的浏览器支持。
div ul + ul {
background-color: #900;
}
与:not
和:nth-sibling
不同,IE7+支持[相邻兄弟姐妹选择器](http://www.w3.org/TR/CSS2/selector.html#adjacent-selectors)。
如果你有JavaScript在页面加载后改变这些属性,你应该看看IE7和IE8实现中的一些已知错误。 见此链接。
对于任何静态网页,这应该是完美的工作。
由于IE6-8不接受:not
,我建议你这样做。
div ul:nth-child(n+2) {
background-color: #900;
}
所以你在其父元素中挑选每一个ul
,除了第一个。
请参考Chris Coyer'的"有用的 :nth-child Recipes"文章,了解更多的`nth-child'例子。