2015-09-27 45 views
1

我想仅将效果应用于标记元素'p'。但我有一个阻止效果的div!第二段必须是蓝色的,怎么办?:nth-​​child()选择器应用于特定元素

<p>The first paragraph.</p> 
<div>The div tag.</div> 
<p>The second paragraph.</p> 
<p>The third paragraph.</p> 
<p><b>Note:</b> Internet Explorer 8 and earlier versions do not support the :nth-child() selector.</p> 

p:nth-child(odd) { background: #ff0000; } 

p:nth-child(even) { background: #0000ff; } 

fiddle

回答

1

您可能正在寻找:nth-of-type选择。

p:nth-of-type(odd) { background: #ff0000; } 
 
p:nth-of-type(even) { background: #0000ff; }
<p>The first paragraph.</p> 
 
<div>The div tag.</div> 
 
<p>The second paragraph.</p> 
 
<p>The third paragraph.</p> 
 
<p><b>Note:</b> Internet Explorer 8 and earlier versions do not support the :nth-child() selector.</p>

+0

ahahha不错不错...很简单,呵呵 –

1

使用:nth-of-type代替。

p:nth-of-type(odd) { 
 
    background: #ff0000; 
 
} 
 
p:nth-of-type(even) { 
 
    background: #0000ff; 
 
}
<p>The first paragraph.</p> 
 
<div>The div tag.</div> 
 
<p>The second paragraph.</p> 
 
<p>The third paragraph.</p> 
 
<p><b>Note:</b> Internet Explorer 8 and earlier versions do not support the :nth-of-type() selector.</p>

另外,选择器L4延伸的:nth-child()语法,允许

:nth-child(odd of p) { background: #ff0000; } 
:nth-child(even of p) { background: #0000ff; } 

...但浏览器不支持它。

+0

感谢听..;) –