我有一个看起来像这样的html元素。.
,它自动使用了id
。
<p>some text...</p>
<p>some text...</p>
<p id="elmt">some text...</p> <!-- I want to put a background -->
<p id="elmt">some text...</p>
<p id="elmt">some text...</p>
<p id="elmt">some text...</p>
我有可能在此上放一个孩子的CSS,看起来像
p#elmt{
background-color: yellow;
}
p#elmt:first-child{
background-color: red;
}
:first-child
有点棘手,许多问题上的问题表明人们用 :first-of-type
来考虑它(与选择器匹配的第一个元素,而这意味着父节点内的第一个元素)。
在这种特定情况下,我建议您稍微反转逻辑并使用
/* set red background for .elmt */
.elmt {
background-color: red;
}
/* set yellow background for .elmt preceded ba another .elmt
- which is all except the first one */
.elmt + .elmt {
background-color: yellow;
}
http://jsfiddle.net/qq8dm/5/
由于 id
是唯一的,因此必须使用类:
<p class="elmt">some text...</p> <!-- I want to put a background -->
<p class="elmt">some text...</p>
<p class="elmt">some text...</p>
<p class="elmt">some text...</p>
然后,您可以使用.
按类:
p.elmt {
background-color: yellow;
}
p.elmt:first-child {
background-color: red;
}
小提琴演示
您无法使用id
属性执行此操作,使用class
属性,
检查JSFIDDLE
id使用单个标识符,其中用作类用于允许多个选择。
作为@pawel答案的替代方法,您可以使用not
选择器。
第一个答案具有更好的支持,但我添加了此供参考。
CSS
p:not(.elmt) + .elmt {
background-color: yellow;
}
.elmt {
background-color: #00f;
}
JSFIDDLE DEMO