Fábio Zangirolami
Fábio Zangirolami

Reputation: 1956

:nth-child() selector apply in specific elements

I want to apply the effect only on tag elements 'p'. but I have a div blocking the effect! The paragraph two must be in blue, how do?

<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

Upvotes: 1

Views: 37

Answers (2)

Oriol
Oriol

Reputation: 288710

Use :nth-of-type instead.

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>

Alternatively, Selectors L4 extends the syntax of :nth-child(), allowing

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

... but browsers don't support it yet.

Upvotes: 1

just95
just95

Reputation: 1099

You are probably looking for the :nth-of-type selector.

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>

Upvotes: 1

Related Questions