如何使用not:first-child selector? [英] How can I use a not:first-child selector?
问题描述
我有 div
标签包含多个 ul
标签。
如果我尝试为第一个 ul
标记设置CSS属性,并且此代码适用:
div ul:first-child {
background-color:#900;
}
当我要为每个 / code>标签,除了第一个,我尝试这样:
div ul:not :first-child {
background-color:#900;
}
也是这样:
< pre class =lang-css prettyprint-override>
div ul:not(:first-child){
background-color:#900;
}
并且:
< pre class =lang-css prettyprint-override>
div ul:first-child:after {
background-color:#900;
}
但没有效果。我如何写CSS:每个元素,除了第一个?
=http://jsfiddle.net/5TKjB/>实际上适用于所有现代浏览器(其中 CSS选择器级别3 是支持的):
div ul:not(:first-child){
background-color:#900;
}
如果您需要支持旧版浏览器, code>:not 选择器的限制(仅接受简单选择器作为参数),则可以使用其他方法:
定义一个规则,其范围比你想要的范围大,然后有条件地撤销,限制其范围到你打算:
div ul {
background-color:#900; / *适用于每个ul * /
}
div ul:first-child {
background-color:transparent; / *限制上一个规则的范围* /
}
所设置的每个CSS属性的默认值。
I have div
tag containing several ul
tags.
If I trying set CSS properties only for the first ul
tag, and this code works:
div ul:first-child {
background-color: #900;
}
When I want set CSS properties for each ul
tag except the first, I tried this:
div ul:not:first-child {
background-color: #900;
}
also this:
div ul:not(:first-child) {
background-color: #900;
}
and this:
div ul:first-child:after {
background-color: #900;
}
But to no effect. How must I write in CSS: "each element, except the first"?
One of the versions you posted actually works for all modern browsers (where CSS selectors level 3 are supported):
div ul:not(:first-child) {
background-color: #900;
}
If you need to support legacy browsers, or if you are hindered by the :not
selector's limitation (it only accepts a simple selector as an argument) then you can use another technique:
Define a rule that has greater scope than what you intend and then "revoke" it conditionally, limiting its scope to what you do intend:
div ul {
background-color: #900; /* applies to every ul */
}
div ul:first-child {
background-color: transparent; /* limits the scope of the previous rule */
}
When limiting the scope use the default value for each CSS attribute that you are setting.
这篇关于如何使用not:first-child selector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!